package o2o.web.actions.order;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.utils.common.*;
import com.jinyou.utils.spring.SpringContextHolder;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import jPush.dao.JPushMessage;
import map.HttpRequest;
import notice.dao.NoticeType;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.agent.PostmanAgentRelationMemory;
import o2o.cache.agent.UserAgentRelationMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.order.*;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanShopRelationMemory;
import o2o.cache.shop.ShopManagerRelationMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.company.postman.ShopSignCompanyFeeInfo;
import o2o.dao.PO.device.door.DeviceCompanyContact;
import o2o.dao.PO.game.*;
import o2o.dao.PO.order.*;
import o2o.dao.PO.policy.INSURANCE_STATUS;
import o2o.dao.PO.policy.PolicyInfo;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.PostmanShopRelation;
import o2o.dao.PO.shop.SHOP_SERIESSALE_TYPE;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.sys.SysSettingValueKey;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.PAY_TYPE;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.PO.wallet.UserWalletFlow;
import o2o.dao.PO.wallet.UserWalletFlowType;
import o2o.dao.TO.policy.InsuredsDto;
import o2o.dao.TO.policy.PolicyOrderDto;
import o2o.dao.VO.hxAccount.HxAccountInfoVO;
import o2o.dao.VO.order.*;
import o2o.service.code.DiscountExchangeCodeService;
import o2o.service.company.postman.DeliverCompanySalarySerivce;
import o2o.service.company.postman.ShopSignCompanyService;
import o2o.service.order.shop.ShopOrderService;
import o2o.system.data.PLAT_SHARE_CITY_ADMIN_MONEY_TYPE;
import o2o.system.data.POSTMAN_IN_CITY_OR_AGENT_DATA;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.jPush.JPushTask;
import o2o.task.order.OrderBakTaskUtils;
import o2o.utils.BackPriceResultInfo;
import o2o.utils.RecordsResult;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.image.OrderImageMan;
import o2o.web.actions.order.thread.OrderThread;
import o2o.web.actions.order.thread.OverOrderThread;
import o2o.web.actions.order.user.UserOrderMan;
import o2o.web.actions.pay.OrderPay;
import o2o.web.actions.pay.PayThreads;
import o2o.web.actions.shop.ShopMan;
import o2o.web.actions.sys.GrabOrderModeMan;
import o2o.web.actions.wallet.UserWalletMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

//订单管理类
@Controller
public class OrderMan {


    /**
     * 获取默认的订单那个时间以内的
     *_
     * @return
     */
    public static long getDefaultQueryOrderTimePoint() {
        if (SYS_SETTINGS.DEFAULT_QUERY_ORDER_IN_DAY != null && SYS_SETTINGS.DEFAULT_QUERY_ORDER_IN_DAY > 0) {
            return DateUtils.getPreDaysOfTimestamp(SYS_SETTINGS.DEFAULT_QUERY_ORDER_IN_DAY.longValue());
        }
        return -1;
    }

    //----------------------订单详情
    public static OrderInfoVO getMultipleParentOrderDetail(String orderNo, UserInfo user) {
        if (!OrderMan.isMultipleParentOrder(orderNo)) {
            return null;
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == info) {
            return null;
        }
        OrderInfoVO infoVO = new OrderInfoVO();
        BeanUtils.copyProperties(info, infoVO);
        if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            if (infoVO.getGrabCompanyId() != null) {
                PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(infoVO.getGrabCompanyId());
                if (companyInfo != null) {
                    infoVO.setGrabCompanyName(companyInfo.getCompanyName());
                }
            }
        }
        List<OrderGameRules> gameList = OrderGameMemory.getInstance().listOfOrderNo(orderNo);

        List<OrderInfoVO> sonOrderList = listOfParentOrderNo(orderNo, user.getUserType());
        if (ValidateUtil.isAbsList(sonOrderList)) {
            infoVO.setOrderInfoList(sonOrderList);
        }
        OrderPayInfo orderPay = OrderPayMemory.getInstance().get(orderNo);
        if (null != orderPay) {
            OrderPayInfoVO payInfoVO = new OrderPayInfoVO();
            BeanUtils.copyProperties(orderPay, payInfoVO);
            infoVO.setOrderPay(payInfoVO);
        }
        return infoVO;
    }

    public static OrderInfoVerifyVO getMultipleOrderDetail(String orderNo, UserInfo user) {
        if (!OrderMan.isMultipleParentOrder(orderNo)) {
            return null;
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == info) {
            return null;
        }
        OrderInfoVerifyVO infoVO = new OrderInfoVerifyVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, infoVO, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (infoVO == null) {
            return infoVO;
        }
//        List<OrderGameRules> gameList = OrderGameMemory.getInstance().listOfOrderNo(orderNo);
//        if (ValidateUtil.isAbsList(gameList)) {
//            List<OrderGameRulesVO> gameVOList = new ArrayList<>();
//            for (int i = 0; i < gameList.size(); i++) {
//                if (null == gameList.get(i)) {
//                    continue;
//                }
//                OrderGameRulesVO vo = new OrderGameRulesVO();
//                try {
//                    ObjectUtils.copyPropertiesExclude(gameList.get(i), vo, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                if (gameList.get(i).getGameType() - GAME_TYPE.RED_PACKET_MONEY == 0 || gameList.get(i).getGameType() - GAME_TYPE.RED_PACKET_FIRST_MONEY == 0) {
//                    RedPacketRecord redPacketRecord = RedPacketRecordMemory.getInstance().getById(gameList.get(i).getGameId());
//                    if (null != redPacketRecord) {
//                        vo.setPacketType(redPacketRecord.getPacketType());
//                    }
//                }
//                gameVOList.add(vo);
//            }
////            infoVO.setGameAward(gameVOList);
//        }
        if (ValidateUtil.isNotNull(infoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
            infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
        }
        //  添加抢单配送公司信息
        if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            if (infoVO.getGrabCompanyId() != null) {
                PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(infoVO.getGrabCompanyId());
                if (companyInfo != null) {
                    infoVO.setGrabCompanyName(companyInfo.getCompanyName());
                }
            }
        }
        List<OrderInfoVO> sonOrderList = listOfParentOrderNo(orderNo, user.getUserType());
        if (ValidateUtil.isAbsList(sonOrderList)) {
            infoVO.setOrderInfoList(sonOrderList);
        }
//
//        OrderPayInfo orderPay = OrderPayMemory.getInstance().get(orderNo);
//        if (null != orderPay) {
//            OrderPayInfoVO payInfoVO = new OrderPayInfoVO();
//            try {
//                ObjectUtils.copyPropertiesExclude(orderPay, payInfoVO, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            infoVO.setOrderPay(payInfoVO);
//        }

        //添加商品列表数据
        List<OrderInfoGoods> goodsList = infoVO.getGoodsList();
        if (!ValidateUtil.isAbsList(goodsList)) {
            infoVO.setGoodsList(getGoodListByOrderNo(orderNo));
        }

        return infoVO;
    }

    // 由父订单获取所有的子订单
    private static List<OrderInfoVO> listOfParentOrderNo(String parentOrderNo, int userType) {
        if (ValidateUtil.isNull(parentOrderNo)) {
            return Collections.emptyList();
        }
        HashSet<String> hashSet = OrderInfoMemory.getInstance().listOfParentOrderNo(parentOrderNo);
        // 获取子订单后
        if (hashSet == null || hashSet.size() == 0) {
            return Collections.emptyList();
        } else {
            List<OrderInfoVO> list = new ArrayList<>();
            for (String orderNo : hashSet) {
                if (ValidateUtil.isNull(orderNo)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = getMultipleSonOrderDetail(orderNo, userType);
                if (orderInfoVO == null) {
                    continue;
                }
                if (orderInfoVO != null) {
                    list.add(orderInfoVO);
                }
            }
            return list;
        }
    }


    // 获取聚合订单子订单详情
    private static OrderInfoVO getMultipleSonOrderDetail(String orderNo, int userType) {
        // 获取订单详情
        OrderInfoVO infoVO = getOrderDetail(orderNo);
        if (infoVO == null) {
            return infoVO;
        }
        String verifyCode = null;
        switch (userType) {
            case UserType.USER: {
                //如果是用户的显示自取或到店验证码
                if (0 == 1 - infoVO.getIsZiQu()) {
                    verifyCode = infoVO.getVerifyCode();
                }
            }
            break;
            case UserType.SHOP_OWNER: {
                OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderNo);
                if (null != orderPayInfo) {
                    infoVO.setShopMoney(orderPayInfo.getShopMoney());
                }
            }
            break;
        }
        infoVO.setVerifyCode(verifyCode);
        //获取收益
        OrderPayInfo orderPay = OrderPayMemory.getInstance().get(orderNo);
        if (null != orderPay) {
            OrderPayInfoVO payInfoVO = new OrderPayInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(orderPay, payInfoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            infoVO.setOrderPay(payInfoVO);
        }

//        if (ValidateUtil.isNotNull(infoVO.getPostManUsername())) {
//            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(infoVO.getPostManUsername());
//            if (null != cityPostman) {
//                CityPostmanVO postmanVO = PostmanMan.getOne(cityPostman);
//                infoVO.setPostmanInfo(postmanVO);
//            }
//        }
        // 获取订单额外信息
        OrderInfoExtra infoExtra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(orderNo);
        infoVO.setOrderInfoExtra(infoExtra);

        return infoVO;

    }


    //获取订单详情
    public static OrderInfoVO getOrderDetail(String orderNo) {
        return getOrderDetail(orderNo, null);
    }

    //获取订单详情
    public static OrderInfoVO getOrderDetail(String orderNo, Integer userType) {
        //订单信息
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == info) {
            if (null != SYS_SETTINGS.USE_BAK_ORDER && 0 == 1 - SYS_SETTINGS.USE_BAK_ORDER) {
                if (null != userType && (0 == UserType.ADMIN - userType || 0 == UserType.SUPER_ADMIN - userType || 0 == UserType.COMPANY - userType)) {
                    // 获取data表的数据
                    QueryCondition query = QueryCondition.getInstance();
                    Expression expressions = Expression.getInstance().addChild("delFlag", 0).addChild("orderNo", orderNo);
                    query.addCondition(expressions);
                    String sql = DaoUtils.getSql(PojoTables.D_ORDER_INFO, query);
                    try {
                        info = (OrderInfo) DataDaoSql.getInstance().getObject(OrderInfo.class, sql);
                    } catch (SQLException e) {
                        e.printStackTrace();
                        return null;
                    }
                    if (null == info) {
                        return null;
                    }
                }
            }

            return null;
        }
        // 订单额外信息
        OrderInfoExtra orderInfoExtra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(orderNo);
        if (null != orderInfoExtra) {
            info.setOrderInfoExtra(orderInfoExtra);
        }

        OrderInfoVO infoVO = new OrderInfoVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, infoVO, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isNotNull(infoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
            infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
        }

        if (ValidateUtil.isNotNull(infoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getPostmanImageUrl())) {
            infoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getPostmanImageUrl());
        }
        //  添加抢单配送公司信息
        if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            if (infoVO.getGrabCompanyId() != null) {
                PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(infoVO.getGrabCompanyId());
                if (companyInfo != null) {
                    infoVO.setGrabCompanyName(companyInfo.getCompanyName());
                }
            }
        }
        //获取订单商品详情_
        List<OrderGoods> list = info.getGoods();
        if (ValidateUtil.isAbsList(list)) {
            List<OrderGoodsVO> voList = new ArrayList<OrderGoodsVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null != list.get(i)) {
                    OrderGoodsVO orderGoodsVO = new OrderGoodsVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(list.get(i), orderGoodsVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    GoodsInfo goodsInfo = GoodsMemory.getInstance().getGoodsInfo(orderGoodsVO.getGoodsId());
//                    orderGoodsVO.setImageUrl(goodsInfo.getImageUrl());
//                    orderGoodsVO.setImageUrlB(goodsInfo.getImageUrlB());
//                    orderGoodsVO.setName(goodsInfo.getName());
//                    orderGoodsVO.setDescs(goodsInfo.getDescs());
//                    orderGoodsVO.setPrice(goodsInfo.getPrice());
//                    orderGoodsVO.setOriginalPrice(goodsInfo.getOriginalPrice());
                    voList.add(orderGoodsVO);
                }
            }

            infoVO.setGoods(voList);
        }


        //服务单相关信息
        if (null != info.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - info.getOrderType()) {
            //标签信息
            List<OrderGoodsLabel> labelList = OrderGoodsLabelMemory.getInstance().listOfOrderNo(orderNo);
            if (ValidateUtil.isAbsList(labelList)) {
                List<OrderGoodsLabelVO> labelVOList = new ArrayList<>();
                for (int i = 0; i < labelList.size(); i++) {
                    if (null == labelList.get(i)) {
                        continue;
                    }
                    OrderGoodsLabelVO vo = new OrderGoodsLabelVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(labelList.get(i), vo, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    labelVOList.add(vo);
                }
                infoVO.setLabelList(labelVOList);
            }

            //服务内容
            List<OrderItems> itemList = OrderItemsMemory.getInstance().listOfOrderNo(orderNo);
            if (ValidateUtil.isAbsList(itemList)) {
                infoVO.setItemList(itemList);
            }

            //图片信息
            List<OrderInfoImageVO> imageList = OrderImageMan.listOfOrderNo(orderNo);
            infoVO.setImageList(imageList);
        }

        // 好管家 订单图片
//        if (null != info.getOrderType() && 0 == ORDER_TYPE.SHOP_SERVICE - info.getOrderType()) {
        if (null != info.getOrderType() && (0 == ORDER_TYPE.SHOP_SERVICE - info.getOrderType() || 0 == ORDER_TYPE.SHOP_RESCUE - info.getOrderType())) {
            List<OrderInfoImageVO> orderInfoImages = OrderImageMan.listOfOrderNo(orderNo);
            if (null != orderInfoImages) {
                infoVO.setImageList(orderInfoImages);
            }
        }
        // 添加环信账号
        HxAccountInfoVO h = new HxAccountInfoVO();
        // 用户的
        if (ValidateUtil.isNotNull(infoVO.getUsername())) {
            UserInfo user = UserInfoMemory.getInstance().getUserInfo(info.getUsername());
            if (user != null) {
                h.setUserId(user.getId()).setName(user.getName()).setUsername(user.getUsername()).setUserHxAccount(user.getHxAccount());
            }
        }
        // 店铺的
        if (ValidateUtil.isID(infoVO.getShopId())) {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(infoVO.getShopId());
            if (null != shopInfo) {
                UserInfo shopUser = UserInfoMemory.getInstance().getUserInfo(shopInfo.getOwnUsername());
                h.setShopName(shopInfo.getShopName()).setShopId(shopInfo.getId());
                if (shopUser != null) {
                    h.setShopUsername(shopUser.getUsername()).setShopHxAccount(shopUser.getHxAccount());
                }
            }
        }
        // 骑手
        if (ValidateUtil.isNotNull(infoVO.getPostManUsername())) {
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(infoVO.getPostManUsername());
            if (cityPostman != null) {
                h.setPostmanId(cityPostman.getId()).setPostmanUsername(cityPostman.getUsername());
                UserInfo user = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
                if (user != null) {
                    h.setPostmanName(user.getName()).setPostmanHxAccount(user.getHxAccount());
                }
            }
        }
        infoVO.setHxAccountInfoVO(h);

        //添加商品列表数据
        List<OrderInfoGoods> goodsList = infoVO.getGoodsList();
        if (!ValidateUtil.isAbsList(goodsList)) {
            infoVO.setGoodsList(getGoodListByOrderNo(orderNo));
        }

        return infoVO;
    }

    public static List<OrderChangeAddressRecordVO> listOrderChangeAddressRecordByOrderNo(String orderNo) {
        QueryCondition query = QueryCondition.getInstance();
        Expression expressions = Expression.getInstance().addChild("delFlag", 0).addChild("orderNo", orderNo);
        query.addCondition(expressions);
        String sql = DaoUtils.getSql(PojoTables.ORDER_ADDRESS_CHANGE_RECORD, query);
        List<OrderChangeAddressRecordInfo> list = null;
        try {
            list = (List<OrderChangeAddressRecordInfo>) UserDaoSql.getInstance().list(OrderChangeAddressRecordInfo.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return Collections.emptyList();
        }
        return list.stream().map(item -> {
            OrderChangeAddressRecordVO vo = new OrderChangeAddressRecordVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
    }


    //------------------订单状态
    //修改订单状态
    public static boolean modifyOrderStatus(String updateUser, String orderNo, int orderStatus, String
            updateTimeStr, String note) {
        if (ValidateUtil.isNull(updateTimeStr)) {
            updateTimeStr = "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(orderStatus)
                .append(",updateUser='").append(updateUser).append("'").append(updateTimeStr).append(" where delFlag = 0 and orderNo = '").append(orderNo).append("'");

        Long tim = DateUtils.getCurrTime();
        OrderStatus status = new OrderStatus(orderNo, orderStatus, updateUser, tim);
        status.setNote(note);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, status);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        //修改订单状态信息缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);

        return true;
    }

    //修改跑腿订单状态
    public static boolean modifyOtherOrderStatus(String updateUser, String orderNo, int orderStatus, String
            updateTimeStr, String note) {
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set orderStatus = ").append(orderStatus)
                .append(",updateUser='").append(updateUser).append("'").append(updateTimeStr).append(" where delFlag = 0 and orderNo = '").append(orderNo).append("'");

        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        //缓存修改
        OtherOrderMemory.getInstance().addOrModify(orderNo);

        return true;
    }

    //修改预订单订单状态
    public static boolean modifyPreOrderStatus(String updateUser, String orderNo, int orderStatus, String
            updateTimeStr, String note) {
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set orderStatus = ").append(orderStatus)
                .append(",updateUser='").append(updateUser).append("'").append(updateTimeStr).append(" where delFlag = 0 and orderNo = '").append(orderNo).append("'");

        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        OrderInfoPreMemory.getInstance().modifyStatus(orderNo);

        return true;
    }

    //修改订单状态
    public static boolean modifyOrderStatus(String updateUser, String orderNo, int orderStatus, String
            updateTimeStr) {
        return modifyOrderStatus(updateUser, orderNo, orderStatus, updateTimeStr, null);
    }


    //----------------------提货验证码
    //获取可用验证吗
    public static String getVerifyCode() {
        //生成取货验证码
        String verifyCode = null;
        int i = 0;
        boolean isGet = false;
        while (i < 10) {
            verifyCode = ToolUtils.getTelCode(); // 6位随机码
            //验证验证码 当前是否唯一
            if (!OrderInfoMemory.getInstance().isVerifyCodeUsed(verifyCode)) {
                isGet = true;
                break;
            }
            i++;
        }
        if (isGet) {
            return verifyCode;
        }

        return null;
    }

    //获取到店消费取货验证码
    public static String getVerifyCodeDaodian() {
        //生成到店消费验证码
        if (SYS_SETTINGS.DAO_DIAN_VERIFY_LENGTH != null && SYS_SETTINGS.DAO_DIAN_VERIFY_LENGTH == 4) {
            // 获取四位的取货码
            List<String> list = VerifyCodeMan.getInstance().getVerifyCodeList();
            if (ValidateUtil.isAbsList(list)) {
                for (String temp : list) {
                    if (!OrderInfoMemory.getInstance().isVerifyCodeUsed(temp)) {
                        return temp;
                    }
                }
            }
        } else {
            String verifyCode = null;
            int i = 0;
            boolean isGet = false;
            while (i < 10) {
                verifyCode = ToolUtils.getVerifyCode(); // 12位随机码
                //验证验证码 当前是否唯一
                if (!OrderInfoMemory.getInstance().isVerifyCodeUsed(verifyCode)) {
                    isGet = true;
                    break;
                }
                i++;
            }
            if (isGet) {
                return verifyCode;
            }
        }
        return null;
    }


    //---------------------自动派单，指定骑手
    public static boolean setOrderPostman(String orderNo, CityPostman postman, String opUsername) {
        if (ValidateUtil.isNull(orderNo) || null == postman) {
            return false;
        }
        if (ValidateUtil.isNull(postman.getUsername())) {
            return false;
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return false;
        }
        // todo 订单状态已改变的，直接跳过
        if (null != orderInfo.getOrderType() && (0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType()
        )) {
            if (0 != ORDER_STATUS.PAYED - orderInfo.getOrderStatus()) {
                return true;
            }
        } else if (0 != ORDER_STATUS.SHOP_SURE - orderInfo.getOrderStatus()) {
            return true;
        }
        UserInfo postmanInfo = UserInfoMemory.getInstance().getUserInfo(postman.getUsername());
        if (null == postmanInfo) {
            return false;
        }
        int orderSts = ORDER_STATUS.POSTMAN_ZHIDING;

        boolean isNeedAccept = true; // 骑手是否需要接单
        if (!OrderMan.systemOperatePostmanNeedAccept()) {
            isNeedAccept = false;
        }

        // 系统派单 0正常订单 1系统派单并直接到骑手进行中
        String postmanSureBySys = "";
        if (!isNeedAccept) {
            orderSts = ORDER_STATUS.POSTMAN_SURE;
            postmanSureBySys = ",postmanSureBySys=1";
        }

        Long time = DateUtils.getCurrTime();

        //保存到订单上
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(orderSts)
                .append(postmanSureBySys)// 系统派单 0正常订单 1系统派单并直接到骑手进行中
                .append(",updateUser = '").append(opUsername).append("',postmanUsername='")
                .append(postmanInfo.getUsername()).append("',postmanName='").append(postmanInfo.getName()).append("',postmanPhone='")
                .append(postmanInfo.getTelPhone())
                .append("',postmanImageUrl='").append(postmanInfo.getSignPhoto()).append("'");

        if (!isNeedAccept) {
            sb.append(" ,postmanSureTime=").append(time);
        }

        // 取货码
        String verifyCode = OrderMan.getVerifyCode();
        if (ValidateUtil.isNotNull(verifyCode)) {
            sb.append(" ,verifyCode='").append(verifyCode).append("' ");
        }

        sb.append(" where delFlag = 0 and  orderNo ='").append(orderNo).append("'");
//        Long time = DateUtils.getCurrTime();
        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_ZHIDING, opUsername, time);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            if (!isNeedAccept) {
                OrderStatus orderStatus2 = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, opUsername, time);
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus2);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("自动派单失败，" + orderNo + "," + postman.getUsername());
            return false;
        }

        //插入订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改订单缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);

        // 给用户发送一条订单通知
        Notice.publishNotice2Person(SysCustomerCache.getInstance().getDefaultKey(), orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");

        // 给骑手发送一条通知
        Notice.publishNotice2Person(SysCustomerCache.getInstance().getDefaultKey(), postman.getUsername(), JPushMessage.POSTMAN, NoticeType.order, "订单信息", "您有新的系统派单（订单编号：" + orderNo + "），请尽快处理");


        //跑腿订单 更新跑腿订单信息里的状态
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(orderSts).append(",updateUser='")
                    .append(opUsername).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                System.out.println("自动派单-跑腿-更新订单状态失败，请稍后再试");
                return false;
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }

        return true;
    }


    //-------------------取消订单
    public static ResultInfo cancelOrder(String sysAppKey, OrderInfo orderInfo, String opUsername, String
            cancelReason) {
        return cancelOrder(sysAppKey, orderInfo, opUsername, cancelReason, true);
    }

    public static ResultInfo cancelOrder(String sysAppKey,
                                         OrderInfo orderInfo, String opUsername, String cancelReason,
                                         Boolean refundAliWxPay//是否需要退微信或者支付宝
    ) {
        return cancelOrder(sysAppKey, orderInfo, opUsername, cancelReason, refundAliWxPay, true, false);
    }

    //取消订单
    public static synchronized ResultInfo cancelOrder(String sysAppKey,
                                                      OrderInfo orderInfo, String opUsername, String cancelReason,
                                                      Boolean refundAliWxPay,//是否需要退微信或者支付宝
                                                      boolean isUpdateOrderStatus,
                                                      boolean isJudgeDuty   // 是否判责
    ) {
        orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getOrderNo());
        if (orderInfo == null || orderInfo.getOrderStatus() == ORDER_STATUS.CANCEL
                || orderInfo.getOrderStatus() == ORDER_STATUS.CANCEL_BY_SYSTEM
                || orderInfo.getOrderStatus() == ORDER_STATUS.PAYED_CANCEL) {
            return new ResultInfo("订单不存在或者已取消");
        }
        // 取消订单
        int orderStatus = ORDER_STATUS.CANCEL;

        // Connection cn = null;
        // if (SYS_SETTINGS.IS_OTHER_POST == 2 && orderInfo.getIsOtherPost() == 1) {
        //     try {
        //         cn = UserDaoSql.getInstance().getConnection();
        //         cn.setAutoCommit(false);
        //         EventInfo eventInfo = new EventInfo();
        //         if (StringUtils.isEmpty(sysAppKey)) {
        //             sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
        //         }
        //         eventInfo.setSysAppKey(sysAppKey).setEventType(EventInfo.EVENT_TYPE_CANCEL_DELIVERY_ORDER)
        //                 .setParams(orderInfo.getOrderNo()).setDelFlag(0);
        //         EventService.getInstance().createEvent(eventInfo, cn);
        //     } catch (Exception e) {
        //         e.printStackTrace();
        //         UserDaoSql.getInstance().rollback(cn);
        //         UserDaoSql.getInstance().close(cn);
        //         return new ResultInfo("退款失败,请晒后重试");
        //     }
        // }
        // 货到付款订单
        // if (null != orderInfo && orderInfo.getIsArrivePay() != null && orderInfo.getIsArrivePay() - 1 == 0) {
        //     // 不处理金额
        // } else {
        //如果店铺余额不够则不能退款
        if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_FINISH || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus() || orderInfo.getOrderStatus() == ORDER_STATUS.OVER) {
            if (0 == orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS || 0 == orderInfo.getOrderType() - ORDER_TYPE.GROUP_BUY) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
                if (null == shopInfo) {
                    // UserDaoSql.getInstance().rollback(cn);
                    // UserDaoSql.getInstance().close(cn);
                    return new ResultInfo("当前店铺不存在无法退款");
                }
                UserWallet userWallet = UserWalletMemory.getInstance().getWallet(shopInfo.getOwnUsername());
                if (null == userWallet) {
                    // UserDaoSql.getInstance().rollback(cn);
                    // UserDaoSql.getInstance().close(cn);
                    return new ResultInfo("当前店铺无余额，无法退款");
                }
                // 获取支付分成流水
                OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
                // 店铺分成的金额
                Double shopMoney = orderPayInfo.getShopMoney() != null ? orderPayInfo.getShopMoney() : orderInfo.getTotalPrice();
                // 如果退款是商家承担所有的钱的话
                if (isJudgeDuty
                        && orderInfo.getOrderType() != null && (orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS == 0 || orderInfo.getOrderType() - ORDER_TYPE.GROUP_ORDER == 0)
                        && SYS_SETTINGS.ORDER_FINISH_BACK_DUTY != null && SYS_SETTINGS.ORDER_FINISH_BACK_DUTY == 1 && ValidateUtil.isAbsDouble(orderPayInfo.getTotalPrice())) {
                    shopMoney = orderPayInfo.getTotalPrice();
                }
                double scale = JYMathDoubleUtils.scale(shopMoney);
                if (JYMathDoubleUtils.sub(userWallet.getMoney(), scale) < 0) {
                    // UserDaoSql.getInstance().rollback(cn);
                    // UserDaoSql.getInstance().close(cn);
                    return new ResultInfo("当前店铺的余额不足，无法退款");
                }
                // 减小销量
                ShopMan.reduceShopOrderCounts(shopInfo.getId(), shopInfo.getOwnUsername(), opUsername);
            }
        }


        //订单是否已被配送员确认送达
        if (ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.OVER == orderInfo.getOrderStatus()) {
            // 一乙的确认送达后，不允许退款
            if (null != SYS_SETTINGS.CUSTOM_SYSTEM_TYPE && 0 == SYS_SETTINGS.CUSTOM_SYSTEM_TYPE - 1) {
                return new ResultInfo("已确认送达后，不允许退款！");
            }
            //恢复分成金额
            ResultInfo resultInfo = OrderPay.refundDistributeMoney(orderInfo.getOrderNo(), opUsername, orderInfo.getOrderType(), isJudgeDuty);
            if (null != resultInfo && !resultInfo.isSuccess()) {
                // UserDaoSql.getInstance().rollback(cn);
                System.out.println("退款失败：" + resultInfo.getError());
            }
            //todo 如果是余额支付的 需要退还余额
        }
        //是否已支付，已支付的需要退款
        if (ValidateUtil.isAbsInteger(orderInfo.getIsPaid()) && 0 == orderInfo.getIsPaid() - 1) { //已经支付过了  需要退款
            double backMoney = orderInfo.getTotalPrice();
            boolean isAlreadyPartCancelMoney = false;
            // 判断订单状态
            if (orderInfo.getIsPartCancelApply() != null && orderInfo.getIsPartCancelApply() != 0) {
                List<OrderCancelInfo> partCancelOrderList = OrderCancelInfoMemory.getInstance().getOrderCancelInfoByParentOrderNo(orderInfo.getOrderNo(), REFUND_APPLY_STATUS.PASS);
                if (ValidateUtil.isAbsList(partCancelOrderList)) {
                    for (OrderCancelInfo info : partCancelOrderList) {
                        if (info == null) {
                            continue;
                        }
                        double back = info.getFcBackTotalMoney() == null ? (info.getBackTotalMoney() == null ? 0 : info.getBackTotalMoney()) : info.getFcBackTotalMoney();
                        backMoney = JYMathDoubleUtils.sub(backMoney, back);
                        isAlreadyPartCancelMoney = true;
                    }
                }
            }
            if (!ValidateUtil.isAbsDouble(backMoney) && backMoney < 0) {
                // UserDaoSql.getInstance().rollback(cn);
                // UserDaoSql.getInstance().close(cn);
                System.out.println("退款后金额小于0");
                return new ResultInfo("退款失败,亲稍后重试~~");
            }
//                Double refundMoney = orderInfo.getTotalPrice();
            Double refundMoney = backMoney;
            Double originalRefundMoney = backMoney;
            //货币金额转换
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY) {//是否使用主币支付 1使用主币支付 0使用外币支付
                //外币支付需要转换
                //外币汇率
                if (ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {
                    //外币计算
                    refundMoney = orderInfo.getFcTotalPrice();
                }
            }
            if (refundAliWxPay) {
                boolean isRefundSuccess = refundMoney > 0 ? false : true;
                if (PAY_TYPE.ARRIVE.equalsIgnoreCase(orderInfo.getPayType())) {
                    isRefundSuccess = true;
                } else if (PAY_TYPE.WALLET.equalsIgnoreCase(orderInfo.getPayType())) {
                    //余额支付  需要退款
                    UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(orderInfo.getUsername());
                    if (null == userinfo) {
                        // UserDaoSql.getInstance().rollback(cn);
                        // UserDaoSql.getInstance().close(cn);
                        return new ResultInfo("退款失败，请稍后再试[用户不存在]");
                    }
                    //用户余额增加
//                        ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderInfo.getUsername(), userinfo.getUserType(), orderInfo.getShopId(), UserWalletMan.REFUND_ADD, orderInfo.getTotalPrice(), orderInfo.getAwardMoney(), opUsername);
                    ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderInfo.getUsername(), userinfo.getUserType(), orderInfo.getShopId(), UserWalletMan.REFUND_ADD, backMoney, 0d, opUsername);
                    if (null != resultInfo) {
                        if (resultInfo.isSuccess()) {
                            //退款成功
                            isRefundSuccess = true;
                        } else {
                            // UserDaoSql.getInstance().rollback(cn);
                            // UserDaoSql.getInstance().close(cn);
                            return new ResultInfo(resultInfo.getError());
                        }
                    } else {
                        // UserDaoSql.getInstance().rollback(cn);
                        // UserDaoSql.getInstance().close(cn);
                        return new ResultInfo("退款失败，请稍后再试[更新用户余额错误]");
                    }
                } else {
//                        isRefundSuccess = OrderPay.refund(orderInfo.getPayType(), orderInfo.getOrderNo(), orderInfo.getOrderNo(), refundMoney, orderInfo.getChargeId());
                    if (isAlreadyPartCancelMoney) {
                        // 退还剩余部分
                        if (ValidateUtil.isAbsDouble(backMoney)) {
                            isRefundSuccess = OrderPay.refundPart(orderInfo.getAgentId(), orderInfo.getPayTypeFlag(),
                                    orderInfo.getPayType(), orderInfo.getOrderNo(), orderInfo.getOrderNo(), orderInfo.getTotalPrice(), backMoney, orderInfo.getChargeId(), true);
                        }
                    } else {
                        if (ValidateUtil.isAbsDouble(refundMoney)) {
                            ResultInfo resultInfo = OrderPay.refundV2(orderInfo.getAgentId(), orderInfo.getPayTypeFlag(),
                                    orderInfo.getPayType(), orderInfo.getOrderNo(), orderInfo.getOrderNo(), refundMoney, originalRefundMoney, orderInfo.getChargeId());
                            if (null != resultInfo) {
                                if (!resultInfo.isSuccess()) {
                                    // UserDaoSql.getInstance().rollback(cn);
                                    // UserDaoSql.getInstance().close(cn);
                                    return resultInfo;
                                }
                                isRefundSuccess = true;
                            } else {
                                // UserDaoSql.getInstance().rollback(cn);
                                // UserDaoSql.getInstance().close(cn);
                                return new ResultInfo("退款失败，请稍后再试。");
                            }
                        }
                    }

                }
                if (isRefundSuccess) {
                    //退款成功了
                } else {
                    // UserDaoSql.getInstance().rollback(cn);
                    // UserDaoSql.getInstance().close(cn);
                    return new ResultInfo("退款失败，请稍后再试");
                }
            }
            orderStatus = ORDER_STATUS.PAYED_CANCEL;
        } else if ((ORDER_TYPE.SHOP_SERVICE - orderInfo.getOrderType() == 0 || ORDER_TYPE.SHOP_RESCUE - orderInfo.getOrderType() == 0) && orderInfo.getOrderStatus() - ORDER_STATUS.SHOP_SELECT == 0 && ValidateUtil.isAbsDouble(orderInfo.getAppointPayMoney())) {
            System.out.println("好管家救援或维修申请退款订单~~~" + orderInfo.getOrderNo());
            // 好管家维修和救援订单~~
            double backMoney = orderInfo.getAppointPayMoney();
            Double refundMoney = backMoney;
            Double originalRefundMoney = backMoney;
            //货币金额转换
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY) {//是否使用主币支付 1使用主币支付 0使用外币支付
                //外币支付需要转换
                //外币汇率
                if (ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {
                    //外币计算
                    refundMoney = orderInfo.getFcTotalPrice();
                }
            }
            if (refundAliWxPay) {
                boolean isRefundSuccess = false;
                if (PAY_TYPE.ARRIVE.equalsIgnoreCase(orderInfo.getAppointPayType())) {
                    isRefundSuccess = true;
                } else if (PAY_TYPE.WALLET.equalsIgnoreCase(orderInfo.getAppointPayType())) {
                    //余额支付  需要退款
                    UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(orderInfo.getUsername());
                    if (null == userinfo) {
                        // UserDaoSql.getInstance().rollback(cn);
                        // UserDaoSql.getInstance().close(cn);
                        return new ResultInfo("退款失败，请稍后再试[用户不存在]");
                    }
                    //用户余额增加
                    ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderInfo.getUsername(), userinfo.getUserType(), orderInfo.getShopId(), UserWalletMan.REFUND_ADD, backMoney, orderInfo.getAwardMoney(), opUsername);
                    if (null != resultInfo) {
                        if (resultInfo.isSuccess()) {
                            //退款成功
                            isRefundSuccess = true;
                        } else {
                            // UserDaoSql.getInstance().rollback(cn);
                            // UserDaoSql.getInstance().close(cn);
                            return new ResultInfo(resultInfo.getError());
                        }
                    } else {
                        // UserDaoSql.getInstance().rollback(cn);
                        // UserDaoSql.getInstance().close(cn);
                        return new ResultInfo("退款失败，请稍后再试[更新用户余额错误]");
                    }
                } else {
                    ResultInfo resultInfo = OrderPay.refundV2(orderInfo.getAgentId(), orderInfo.getPayTypeFlag(),
                            orderInfo.getAppointPayType(), orderInfo.getAppointOrderNo(), orderInfo.getOrderNo(), refundMoney, originalRefundMoney, orderInfo.getChargeId());
                    if (null != resultInfo) {
                        if (!resultInfo.isSuccess()) {
                            // UserDaoSql.getInstance().rollback(cn);
                            // UserDaoSql.getInstance().close(cn);
                            return resultInfo;
                        }
                        isRefundSuccess = true;
                    } else {
                        // UserDaoSql.getInstance().rollback(cn);
                        // UserDaoSql.getInstance().close(cn);
                        return new ResultInfo("退款失败，请稍后再试。");
                    }
                }
                if (isRefundSuccess) {
                    //退款成功了
                    System.out.println("好管家订单取消成功了~~~~" + orderInfo.getOrderNo());
                } else {
                    // UserDaoSql.getInstance().rollback(cn);
                    // UserDaoSql.getInstance().close(cn);
                    return new ResultInfo("退款失败，请稍后再试");
                }
            }
            orderStatus = ORDER_STATUS.CANCEL;
        } else {
            orderStatus = ORDER_STATUS.CANCEL;
        }
        // }
//
//            //如果店铺余额不够则不能退款
//            if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_FINISH || orderInfo.getOrderStatus() == ORDER_STATUS.OVER) {
//                if (0 == orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS || 0 == orderInfo.getOrderType() - ORDER_TYPE.GROUP_BUY) {
//                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
//                    if (null == shopInfo) {
//                        return new ResultInfo("当前店铺不存在无法退款");
//                    }
//                    UserWallet userWallet = UserWalletMemory.getInstance().getWallet(shopInfo.getOwnUsername());
//                    if (null == userWallet) {
//                        return new ResultInfo("当前店铺无余额，无法退款");
//                    }
//                    // 获取支付分成流水
//                    OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
//                    // 店铺分成的金额
//                    Double shopMoney = orderPayInfo.getShopMoney() != null ? orderPayInfo.getShopMoney() : orderInfo.getTotalPrice();
//                    double scale = JYMathDoubleUtils.scale(shopMoney);
//                    if (JYMathDoubleUtils.sub(userWallet.getMoney(), scale) < 0) {
//                        return new ResultInfo("当前店铺的余额不足，无法退款");
//                    }
//
//
//                    //更新店铺销量
//                    ShopMan.addShopOrderCounts(shopInfo.getId(), shopInfo.getOwnUsername(), opUsername);
//                }
//            }
//
//
//        //订单是否已被配送员确认送达
//        if (ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
//                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
//                || ORDER_STATUS.OVER == orderInfo.getOrderStatus()) {
//            //恢复分成金额
//            ResultInfo resultInfo = OrderPay.refundDistributeMoney(orderInfo.getOrderNo(), opUsername, orderInfo.getOrderType());
//            if (null != resultInfo && !resultInfo.isSuccess()) {
//                System.out.println("退款失败：" + resultInfo.getError());
//            }
//
//            //todo 如果是余额支付的 需要退还余额
//        }
//
//        int orderStatus = ORDER_STATUS.CANCEL;
//        //是否已支付，已支付的需要退款
//        if (ValidateUtil.isAbsInteger(orderInfo.getIsPaid()) && 0 == orderInfo.getIsPaid() - 1) {//已经支付过了  需要退款
//            Double refundMoney = orderInfo.getTotalPrice();
//            //货币金额转换
//            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY) {//是否使用主币支付 1使用主币支付 0使用外币支付
//                //外币支付需要转换
//                //外币汇率
//                if (ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {
//                    //外币计算
//                    refundMoney = orderInfo.getFcTotalPrice();
//                }
//            }
//            if (refundAliWxPay) {
//                boolean isRefundSuccess = false;
//                if (PAY_TYPE.WALLET.equalsIgnoreCase(orderInfo.getPayType())) {
//                    //余额支付  需要退款
//                    UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(orderInfo.getUsername());
//                    if (null == userinfo) {
//                        return new ResultInfo("退款失败，请稍后再试[用户不存在]");
//                    }
//                    //用户余额增加
//                    ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderInfo.getUsername(), userinfo.getUserType(), orderInfo.getShopId(), UserWalletMan.REFUND_ADD, orderInfo.getTotalPrice(), orderInfo.getAwardMoney(), opUsername);
//                    if (null != resultInfo) {
//                        if (resultInfo.isSuccess()) {
//                            //退款成功
//                            isRefundSuccess = true;
//                        } else {
//                            return new ResultInfo(resultInfo.getError());
//                        }
//                    } else {
//                        return new ResultInfo("退款失败，请稍后再试[更新用户余额错误]");
//                    }
//                } else {
//                    isRefundSuccess = OrderPay.refund(orderInfo.getPayType(), orderInfo.getOrderNo(), refundMoney, orderInfo.getChargeId());
//                }
//                if (isRefundSuccess) {
//                    //退款成功了
//                } else {
//                    return new ResultInfo("退款失败，请稍后再试");
//                }
//            }
//
//            orderStatus = ORDER_STATUS.PAYED_CANCEL;
//        } else {
//            orderStatus = ORDER_STATUS.CANCEL;
//        }

//        ResultInfo resultInfo = OrderMan.cancelOrder(orderInfo, opUsername, cancelReason, orderStatus, true);
        if (OrderMan.isMultipleParentOrder(orderInfo)) {
            System.out.println("父订单取消了~~~~----->" + orderInfo.getOrderNo());
            cancelMultipleOrderSonDirect(orderInfo.getOrderNo(), opUsername, cancelReason, orderStatus, true, isUpdateOrderStatus);
        }
        ResultInfo resultInfo = cancelOrderDirect(orderInfo, opUsername, cancelReason, orderStatus, true, isUpdateOrderStatus);

        if (null != resultInfo && resultInfo.isSuccess()) {
            // 哒哒的退款
            System.out.println("哒哒退款发送了吗~~~~" + SYS_SETTINGS.IS_OTHER_POST + ":" + orderInfo.getIsOtherPost());
            if (SYS_SETTINGS.IS_OTHER_POST == 2 && orderInfo.getIsOtherPost() == 1) {
                ShopOrderService.getInstance().cancelDeliveryOrderData(sysAppKey, orderInfo, true);
            }
            //发送一条订单通知
//            Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已取消");
//            //极光推送
//            JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已取消");
//            jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//            JPushTask.jPushMessageList.add(jPushMessage);

            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已取消");


            //推送给锁匠
            if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType() && ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
                Notice.publishNotice2Person(sysAppKey, orderInfo.getPostManUsername(), JPushMessage.POSTMAN, NoticeType.order, "工单信息", "您的订单（工单编号：" + orderInfo.getOrderNo() + "）已取消");
            } else if (ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
                // 有配送员的话，推送给配送员
                Notice.publishNotice2Person(sysAppKey, orderInfo.getPostManUsername(), JPushMessage.POSTMAN, "-4", NoticeType.order, "订单已取消", "您的订单（订单编号：" + orderInfo.getOrderNo() + "）订单已取消", orderInfo.getOrderNo());
            }

            return resultInfo;
        }
        // else {
        //     UserDaoSql.getInstance().rollback(cn);
        // }
        // if (SYS_SETTINGS.IS_OTHER_POST == 2 && orderInfo.getIsOtherPost() == 1) {
        //     // 提交事务
        //     try {
        //         cn.commit();
        //     } catch (Exception e) {
        //         e.printStackTrace();
        //     } finally {
        //         UserDaoSql.getInstance().close(cn);
        //     }
        // }

        // 将订单加入备份线程
        OrderBakTaskUtils.addOrder(orderInfo.getOrderNo());
        return resultInfo;
    }

    public static void cancelMultipleOrderSonDirect(String orderNo, String updateUser, String
            cancelReason, Integer orderStatus, boolean foreCancel, boolean isUpdateOrderStatus) {
        HashSet<String> orderSet = OrderInfoMemory.getInstance().getOrderNoByPayNo(orderNo);
        if (orderSet != null && orderSet.size() > 0) {
            for (String tNo : orderSet) {
                if (tNo.equals(orderNo)) { // 主订单在外边已经取消过了 不在进行取消订单的操作了
                    continue;
                }
                OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(tNo);
                if (orderInfo == null) {
                    continue;
                }
                cancelOrderDirect(orderInfo, updateUser, cancelReason, orderStatus, foreCancel, isUpdateOrderStatus);
            }
        }
    }

    //取消订单
    public static ResultInfo cancelOrderDirect(OrderInfo orderInfo, String updateUser, String
            cancelReason, Integer orderStatus, boolean foreCancel, boolean isUpdateOrderStatus) {
//        if (ValidateUtil.isNull(orderNo)) {
//            return new ResultInfo("订单编号不能为空");
//        }
//
//        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        // 货到付款的
        boolean isNotArrayPay = true;
        if (orderInfo != null && orderInfo.getIsArrivePay() != null && orderInfo.getIsArrivePay() == 1) {
            isNotArrayPay = false;
        }

        if (null == orderInfo) {
            return new ResultInfo("该订单不存在");
        }
        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM) {
            return new ResultInfo("该订单已被取消");
        }

        if (!foreCancel) {
            if (status == ORDER_STATUS.CANCEL
                    || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                    || status == ORDER_STATUS.OVER
                    || status == ORDER_STATUS.PEISONG
                    || status == ORDER_STATUS.POSTMAN_SURE
                    || status == ORDER_STATUS.POSTMAN_ZHIDING
                    || status == ORDER_STATUS.POSTMAN_FINISH
                    || status == ORDER_STATUS.SHOP_REFUSED
                    || status == ORDER_STATUS.SHOP_FINISH
                    || status == ORDER_STATUS.SHOP_SURE) {
                return new ResultInfo("当前状态下不允许取消订单");
            }
        }
        if (isUpdateOrderStatus) {
            String updateTimeStr = ",postFailReason = '" + cancelReason + "',postmanFinishTime=" + DateUtils.getCurrTime();
            if (ORDER_STATUS.userWaitForPostSet.contains(status) || ORDER_STATUS.finishDeliverSet.contains(status)) {
                updateTimeStr += ",isPostingCancel = 1 ";
            }
            if (!OrderMan.modifyOrderStatus(updateUser, orderInfo.getOrderNo(), orderStatus, updateTimeStr, cancelReason)) {
                return new ResultInfo("操作失败，请稍后再试");
            }
        }


        //支付流水中取消订单
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderPay).append(" set isOrderCancel = 1,updateUser = '").append(updateUser).append("' where delFlag = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //修改缓存
        OrderPayMemory.getInstance().modify(orderInfo.getOrderNo());
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderInfo.getOrderNo());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        //设置支付流水中已退款
        StringBuffer sbFlow = new StringBuffer();
//        sbFlow.append("update ").append(PojoTables.USER_WALLET_FLOW).append(" set isRefund = 1,updateUser = '").append(updateUser).append("' where delFlag = 0 and isRefund = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
        sbFlow.append("update ").append(PojoTables.USER_WALLET_FLOW).append(" set isRefund = 1,updateUser = '").append(updateUser).append("' where delFlag = 0 and isRefund = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("'").append(" and username ='").append(orderInfo.getUsername()).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sbFlow.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //取出支付中的
        PayThreads.map.remove(orderInfo.getOrderNo());
        //检查订单中清除
        OrderThread.map.remove(orderInfo.getOrderNo());

        // 处理用户是否有订单
        UserOrderMan.doUserOrder(orderInfo.getUsername(), updateUser);

//        //跑腿订单修改订单状态
//        if (0 == -2 - orderInfo.getShopId()) {
//            //修改跑腿订单订单状态
//            Order.modifyOtherOrderStatus(updateUser, orderInfo.getOrderNo(), orderStatus, "", null);
//        }

        //跑腿订单修改订单状态
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())) {
            // 是不是配送中取消的订单
            String updateIsPostCancel = "";
            if (ORDER_STATUS.userWaitForPostSet.contains(status) || ORDER_STATUS.finishDeliverSet.contains(status)) {
                updateIsPostCancel = ",isPostingCancel = 1 ";
            }
            //修改跑腿订单订单状态
            OrderMan.modifyOtherOrderStatus(updateUser, orderInfo.getOrderNo(), orderStatus, updateIsPostCancel, null);
            // 修改订单
            if (orderInfo.getOrderType() - ORDER_TYPE.PERSON_TRANSPORT == 0 && SYS_SETTINGS.HAS_BAO_XIAN == 1 && orderInfo.getIsBuyInsurance() != null && orderInfo.getIsBuyInsurance() - 1 == 0) {
                OrderMan.cancelPolicy(orderInfo.getOrderNo(), updateUser);
            }
        }



        // end
        //开锁工单 修改工单订单状态
        if (null != orderInfo.getOrderType() && 0 == 1 - ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            StringBuffer sbPre = new StringBuffer();
            sbPre.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set orderStatus = ").append(orderStatus)
                    .append(",updateUser='").append(updateUser).append("' where delFlag=0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbPre.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            OrderInfoPreMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        }
        //TODO：分销处理-订单取消
        if (null != SYS_SETTINGS.IS_OPEN_DISTRIBUTION && 0 == 1 - SYS_SETTINGS.IS_OPEN_DISTRIBUTION) {
            String requrstStr = HttpRequest.sendPost(SYS_CONFIG_PATH.FEN_XIAO_SERVICE_URL + "/api/distribute/order/commision/cancel"
                    , "orderNo=" + orderInfo.getOrderNo() + "&sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY);
            DeviceCompanyContact companyContact = new Gson().fromJson(requrstStr, DeviceCompanyContact.class);
            if (null == companyContact) {
                System.out.println("分销处理-订单取消失败 " + orderInfo.getOrderNo());
            }
            if (0 == 1 - companyContact.getStatus()) {
                System.out.println("分销处理-订单取消成功 " + orderInfo.getOrderNo());
            }
        }
        // TODO: 积分抵现-订单取消
        if (SYS_SETTINGS.IS_OPEN_INTEGRAL != null && SYS_SETTINGS.IS_OPEN_INTEGRAL == 1 && ValidateUtil.isAbsLong(orderInfo.getIntegral())) {
            try {
                String params = "sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY +
                        "&orderNo=" + orderInfo.getOrderNo() + "&username=" + orderInfo.getUsername();
                String respStr = HttpRequest.sendPost(SYS_CONFIG_PATH.INTEGRAL_SERVICE_URL + "/api/distribute/integral/records/cancel/order", params);
                if (ValidateUtil.isNull(respStr)) {
                    System.out.println("取消订单还原积分失败" + orderInfo.getOrderNo());
                }
                RecordsResult recordsResult = new Gson().fromJson(respStr, RecordsResult.class);
                if (recordsResult != null && recordsResult.getStatus() == 1) {
                    System.out.println("取消订单--还原积分成功" + orderInfo.getOrderNo());
                } else {
                    System.out.println("取消订单--还原积分失败--->" + orderInfo.getOrderNo() + ";error:" + recordsResult.getError());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 回退兑换码
        if (ValidateUtil.isNotNull(orderInfo.getDiscountExchangeCode())) {
            SpringContextHolder.getBean(DiscountExchangeCodeService.class).orderCancelBackDisExchangeCode(orderInfo.getDiscountExchangeCode(), orderInfo.getOrderNo(), "admin");
        }
        // 将订单加入备份线程
        OrderBakTaskUtils.addOrder(orderInfo.getOrderNo());

        return new ResultInfo();
    }

    //取消维修订单
    public static ResultInfo cancelRepairOrder(OrderInfo orderInfo, String updateUser, String
            cancelReason, Integer orderStatus, String opUsername, boolean foreCancel) {
        if (null == orderInfo) {
            return new ResultInfo("该订单不存在");
        }
        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM) {
            return new ResultInfo("该订单已被取消");
        }

        if (!foreCancel) {
            if (status == ORDER_STATUS.CANCEL
                    || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                    || status == ORDER_STATUS.OVER
                    || status == ORDER_STATUS.PEISONG
                    || status == ORDER_STATUS.POSTMAN_SURE
                    || status == ORDER_STATUS.POSTMAN_ZHIDING
                    || status == ORDER_STATUS.POSTMAN_FINISH
                    || status == ORDER_STATUS.SHOP_REFUSED
                    || status == ORDER_STATUS.SHOP_FINISH
                    || status == ORDER_STATUS.SHOP_SURE) {
                return new ResultInfo("当前状态下不允许取消订单");
            }
        }
        Double appointPayMoney = orderInfo.getAppointPayMoney();
        Double originalRefundMoney = appointPayMoney;
        // 退钱
        if (ValidateUtil.isAbsDouble(appointPayMoney) && ValidateUtil.isAbsLong(orderInfo.getAppointPayDoneTime()) && ValidateUtil.isAbsLong(orderInfo.getAppointPayTime())) { //已经支付过了  需要退款
            boolean isRefundSuccess = false;
            if (PAY_TYPE.WALLET.equalsIgnoreCase(orderInfo.getPayType())) {
                //余额支付  需要退款
                UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(orderInfo.getUsername());
                if (null == userinfo) {
                    return new ResultInfo("退款失败，请稍后再试[用户不存在]");
                }
                //用户余额增加
                ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderInfo.getUsername(), userinfo.getUserType(), orderInfo.getShopId(), UserWalletMan.REFUND_ADD, orderInfo.getAppointPayMoney(), orderInfo.getAwardMoney(), opUsername);
                if (null != resultInfo) {
                    if (resultInfo.isSuccess()) {
                        //退款成功
                        isRefundSuccess = true;
                    } else {
                        return new ResultInfo(resultInfo.getError());
                    }
                } else {
                    return new ResultInfo("退款失败，请稍后再试[更新用户余额错误]");
                }
            } else {
//                isRefundSuccess = OrderPay.refund(orderInfo.getAppointPayType(), orderInfo.getAppointOrderNo(), orderInfo.getOrderNo(), appointPayMoney, orderInfo.getChargeId());
                ResultInfo resultInfo = OrderPay.refundV2(orderInfo.getAgentId(), orderInfo.getPayTypeFlag(),
                        orderInfo.getAppointPayType(), orderInfo.getAppointOrderNo(), orderInfo.getOrderNo(), appointPayMoney, originalRefundMoney, orderInfo.getChargeId());// 维修订单
                if (null != resultInfo) {
                    if (!resultInfo.isSuccess()) {
                        return resultInfo;
                    }
                    isRefundSuccess = true;
                } else {
                    return new ResultInfo("退款失败，请稍后再试。");
                }
            }
            if (isRefundSuccess) {
                //退款成功了
            } else {
                return new ResultInfo("退款失败，请稍后再试");
            }
            orderStatus = ORDER_STATUS.PAYED_CANCEL;
        } else {
            orderStatus = ORDER_STATUS.CANCEL;
        }
        // 完成

        String updateTimeStr = ",postFailReason = '" + cancelReason + "',postmanFinishTime=" + DateUtils.getCurrTime();
        if (!OrderMan.modifyOrderStatus(updateUser, orderInfo.getOrderNo(), orderStatus, updateTimeStr, cancelReason)) {
            return new ResultInfo("操作失败，请稍后再试");
        }

        //支付流水中取消订单
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderPay).append(" set isOrderCancel = 1,updateUser = '").append(updateUser).append("' where delFlag = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //修改缓存
        OrderPayMemory.getInstance().modify(orderInfo.getOrderNo());
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderInfo.getOrderNo());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        // 设置用户订单
        UserOrderMan.doUserOrder(orderInfo.getUsername(), updateUser);

        //设置支付流水中已退款
        StringBuffer sbFlow = new StringBuffer();
        sbFlow.append("update ").append(PojoTables.USER_WALLET_FLOW).append(" set isRefund = 1,updateUser = '").append(updateUser).append("' where delFlag = 0 and isRefund = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sbFlow.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //取出支付中的
        PayThreads.map.remove(orderInfo.getOrderNo());
        //检查订单中清除
        OrderThread.map.remove(orderInfo.getOrderNo());

        //跑腿订单修改订单状态
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())) {
            //修改跑腿订单订单状态
            OrderMan.modifyOtherOrderStatus(updateUser, orderInfo.getOrderNo(), orderStatus, "", null);
        }


        return new ResultInfo();
    }


    //-------------------完成订单
    //完成订单
    public static boolean finishOrder(String orderNo, String opUsername, OrderInfo orderInfo) {
        if (ValidateUtil.isNull(orderNo)) {
            return false;
        }
        if (ValidateUtil.isNull(opUsername)) {
            return false;
        }
        String updateTimeStr = ",userFinishTime=" + DateUtils.getCurrTime();
        // 子订单  不能直接完成 需要父订单完成才行
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            return false;
        }
        //
        if (OrderMan.isMultipleParentOrder(orderInfo)) {
            // 聚合订单
            boolean flag = true;
            try {
                OrderMan.modifyOrderStatusMultipleOrder(opUsername, orderNo, ORDER_STATUS.OVER, updateTimeStr, "");
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }
            if (!flag) {
                return false;
            }
        } else {
            if (!OrderMan.modifyOrderStatus(opUsername, orderNo, ORDER_STATUS.OVER, updateTimeStr)) {
                return false;
            }
            // 跑腿订单
            if (null != orderInfo.getOrderType() && (0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType() || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType() || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType() || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())) {
                OrderMan.modifyOtherOrderStatus(opUsername, orderNo, ORDER_STATUS.OVER, updateTimeStr, null);
            }
        }


        if (null != orderInfo && null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            //如果是转单 则需要修改原订单信息
            OrderInfoPre preInfo = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
            if (null != preInfo) {
                String finishTime = ",userFinishTime=" + DateUtils.getCurrTime();
                OrderMan.modifyPreOrderStatus(opUsername, orderNo, ORDER_STATUS.OVER, finishTime, null);
            }
        }
        //TODO:分销处理-订单完成
        if (null != SYS_SETTINGS.IS_OPEN_DISTRIBUTION && 0 == 1 - SYS_SETTINGS.IS_OPEN_DISTRIBUTION) {
            try {
                String requrstStr = HttpRequest.sendPost(SYS_CONFIG_PATH.FEN_XIAO_SERVICE_URL + "/api/distribute/order/commision/finish"
                        , "orderNo=" + orderInfo.getOrderNo() + "&sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY);
                DeviceCompanyContact companyContact = new Gson().fromJson(requrstStr, DeviceCompanyContact.class);
                if (null == companyContact) {
                    System.out.println("分销失败 " + orderInfo.getOrderNo());
                }
                if (0 == 1 - companyContact.getStatus()) {
                    System.out.println("分销处理-订单完成 " + orderInfo.getOrderNo());
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("分销处理失败");
            }
        }

        //分享商品处理
        if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SHARE_GOODS_ORDER - orderInfo.getOrderType()) {
            shareGoodsOp(orderNo, orderInfo.getUsername(), opUsername);
        }
        // 商家发送的指定营销券
//        sendOrderShopPacket(orderInfo, orderInfo.getShopId(), orderInfo.getUsername());

        // 将订单加入备份线程
        OrderBakTaskUtils.addOrder(orderNo);
        // 删除验证码
        if (ValidateUtil.isNotNull(orderInfo.getVerifyCode())) {
            OrderInfoMemory.getInstance().removeVerifyCode(orderInfo.getOrderNo(), orderInfo.getVerifyCode());
        }
        return true;
    }



    // ***********************订单取消部分商品*********************************
    // 部分商品退货处理
    public static BackPriceResultInfo doBackGoods(OrderInfo orderInfo, String goodsInfoJson,
                                                  boolean isBackPacketPrice, String orderNo, String backOrderNo, String username, long cTime,
                                                  int allTotalCount, Connection conn) {
        if (null == orderInfo) {
            return new BackPriceResultInfo("订单信息不能为空");
        }
        // 检测是否退过
        List<OrderCancelInfo> list = OrderCancelInfoMemory.getInstance().getOrderCancelInfoByParentOrderNo(orderNo, null);
        if (SYS_SETTINGS.ORDER_CAN_PART_CANCEL_MULTI == 0 && ValidateUtil.isAbsList(list)) {
            return new BackPriceResultInfo("已经申请过退款，无法再次申请");
        }
        if (ValidateUtil.isAbsList(list)) {
            list = list.stream().filter(b -> b.getIsPartCancelApply() != null && b.getIsPartCancelApply() != REFUND_APPLY_STATUS.NO_PASS).collect(Collectors.toList());
        }
        // 退款商品
        List<OrderGoodsVO> goodsVOList;
        try {
            goodsVOList = new Gson().fromJson(goodsInfoJson, new TypeToken<List<OrderGoodsVO>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
            return new BackPriceResultInfo("商品解析失败");
        }
        if (!ValidateUtil.isAbsList(goodsVOList)) {
            return new BackPriceResultInfo("退还商品解析失败");
        }
        // 处理掉无用信息
        List<OrderGoodsVO> backGoodsVOList = new ArrayList<>();
        for (OrderGoodsVO orderGoodsVO : goodsVOList) {
            if (ValidateUtil.isNotID(orderGoodsVO.getId())) {
                return new BackPriceResultInfo("退款订单商品id不能为空");
            }
            if (!ValidateUtil.isAbsInteger(orderGoodsVO.getTotalCount())) {
                return new BackPriceResultInfo("退换件数不能为空");
            }
//            if (ValidateUtil.isNotAbsLong(orderGoodsVO.getGoodsId())) {
//                continue;
//            }
//            if (ValidateUtil.isNotAbsInteger(orderGoodsVO.getTotalCount())) {
//                continue;
//            }
            backGoodsVOList.add(orderGoodsVO);
        }
        if (!ValidateUtil.isAbsList(backGoodsVOList)) {
            return new BackPriceResultInfo("暂无有效提交信息，请核实");
        }
//        // 商品比较处理
//        List<OrderGoods> goodsList = OrderGoodsMemory.getInstance().listOfOrderNo(orderNo);
//        Map<String, OrderGoods> goodsMap = new HashMap<>();
//        if (!ValidateUtil.isAbsList(goodsList)) {
//            return new BackPriceResultInfo("获取商品信息失败");
//        } else {
//            for (OrderGoods o : goodsList) {
//                if (ValidateUtil.isNotAbsLong(o.getGoodsSpecsId())) {
//                    goodsMap.put(o.getGoodsId() + "", o);
//                } else {
//                    goodsMap.put(o.getGoodsId() + "_" + o.getGoodsSpecsId(), o);
//                }
//            }
//        }

        Integer backTotalCount = 0;
        Double backTotalPrice = 0.0D;
        Double backTotalGoodsPrice = 0.0d;
        Double backTotalPacketPrice = 0.0d;

        for (OrderGoodsVO goodsVO : backGoodsVOList) {
            OrderGoods orderGoodsDB = getOrderGoodsByOrderNOAndId(orderNo, goodsVO.getId());
            if (orderGoodsDB == null) {
                return new BackPriceResultInfo("订单商品不存在，请核实");
            }
            List<OrderCancelGoodsInfo> orderCancelGoodsInfoList = getAlreadyApplyListOrderCancelGoodsByOrderNo(orderNo, goodsVO.getId());
            int total = 0;
            // 之前所有退的
            if (ValidateUtil.isAbsList(orderCancelGoodsInfoList)) {
                for (OrderCancelGoodsInfo info : orderCancelGoodsInfoList) {
                    if (info == null) {
                        continue;
                    }
                    if (!ValidateUtil.isAbsInteger(info.getBackTotalCount())) {
                        continue;
                    }
                    total += info.getBackTotalCount();
                }
            }
            // 现在退的
            total += goodsVO.getTotalCount();
            allTotalCount += goodsVO.getTotalCount();
            if (total > orderGoodsDB.getTotalCount()) {
                return new BackPriceResultInfo("件数不能大于购买件数");
            }
            // 件数合理
            // 1. 计算总钱数
            backTotalCount += goodsVO.getTotalCount();
            backTotalGoodsPrice = JYMathDoubleUtils.add(backTotalGoodsPrice, goodsVO.getTotalCount() * orderGoodsDB.getGoodsPrice());
            backTotalPacketPrice = JYMathDoubleUtils.add(backTotalPacketPrice, goodsVO.getTotalCount() * orderGoodsDB.getPacketPrice());

            // 2. 插入数据库
            OrderCancelGoodsInfo orderCancelGoodsInfo = new OrderCancelGoodsInfo();
            orderCancelGoodsInfo.setId(null).setCreateUser(username).setCreateTime(cTime).setDelFlag(0).setName(orderGoodsDB.getName())
                    .setOrderNo(backOrderNo).setParentOrderNo(orderNo);
            orderCancelGoodsInfo.setGoodsId(orderGoodsDB.getGoodsId()).setGoodsSpecsId(orderGoodsDB.getGoodsSpecsId());
            orderCancelGoodsInfo.setImageUrl(getImageUrl(orderGoodsDB.getImageUrl()));
            orderCancelGoodsInfo.setPacketPrice(orderGoodsDB.getPacketPrice());
            orderCancelGoodsInfo.setGoodsPrice(orderGoodsDB.getGoodsPrice());
            orderCancelGoodsInfo.setShopId(orderGoodsDB.getShopId());
            orderCancelGoodsInfo.setIsBackApply(REFUND_APPLY_STATUS.APPLY);
            orderCancelGoodsInfo.setBackTotalCount(goodsVO.getTotalCount());
            orderCancelGoodsInfo.setBackTotalGoodsPrice(JYMathDoubleUtils.mul(orderCancelGoodsInfo.getBackTotalCount() == null ? 0 : orderCancelGoodsInfo.getBackTotalCount(), orderCancelGoodsInfo.getGoodsPrice()));
            orderCancelGoodsInfo.setBackTotalGoodsPrice(0.0d);
            if (isBackPacketPrice) {
                orderCancelGoodsInfo.setBackTotalPacketPrice(JYMathDoubleUtils.mul(orderCancelGoodsInfo.getBackTotalCount() == null ? 0 : orderCancelGoodsInfo.getBackTotalCount(), orderCancelGoodsInfo.getPacketPrice()));
            }
            orderCancelGoodsInfo.setBackTotalMoney(JYMathDoubleUtils.add(orderCancelGoodsInfo.getBackTotalGoodsPrice(), orderCancelGoodsInfo.getBackTotalPacketPrice()))
                    .setParentOrderGoodsId(orderGoodsDB.getId());
            try {
                UserDaoSql.getInstance().saveObj(PojoTables.ORDER_CANCEL_GOODS_INFO, orderCancelGoodsInfo, conn);
            } catch (SQLException e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                return new BackPriceResultInfo("存储退还商品信息失败，请稍后重试");
            }
        }
//        for (OrderGoodsVO goodsVO : backGoodsVOList) {
//            OrderGoods temp = null;
//            if (ValidateUtil.isAbsLong(goodsVO.getGoodsSpecsId())) {
//                temp = goodsMap.get(goodsVO.getGoodsId() + "_" + goodsVO.getGoodsSpecsId());
//            } else {
//                temp = goodsMap.get(goodsVO.getGoodsId());
//            }
//            if (ValidateUtil.isNull(temp)) {
//                return new BackPriceResultInfo("订单商品中查无此商品");
//            } else {
//                if (temp.getTotalCount() < goodsVO.getTotalCount()) {
//                    return new BackPriceResultInfo("退还件数大于购买件数");
//                } else {
//                    backTotalCount += goodsVO.getTotalCount();
//                    backTotalGoodsPrice = JYMathDoubleUtils.add(backTotalGoodsPrice, goodsVO.getTotalCount() * temp.getGoodsPrice());
//                    backTotalPacketPrice = JYMathDoubleUtils.add(backTotalPacketPrice, goodsVO.getTotalCount() * temp.getPacketPrice());
//                }
//            }
//        }
//        if (backTotalCount - orderInfo.getTotalCount() == 0) {
        if (allTotalCount - orderInfo.getTotalCount() >= 0) {
            UserDaoSql.getInstance().rollback(conn);
            return new BackPriceResultInfo("退还全部商品请选择取消订单");
        }
        backTotalPrice = JYMathDoubleUtils.add(backTotalGoodsPrice, backTotalPacketPrice);
        BackPriceResultInfo backPriceResultInfo = new BackPriceResultInfo();
        backPriceResultInfo.setBackTotalCount(backTotalCount).setBackTotalGoodsPrice(backTotalGoodsPrice).setBackTotalPacketPrice(backTotalPacketPrice).setBackTotalPrice(backTotalPrice).setOrderGoodsVOList(backGoodsVOList).setSuccess(true);

//        if (null != goodsVOList && goodsVOList.size() > 0) {
//            for (int i = 0; i < goodsVOList.size(); i++) {
//                OrderGoodsVO orderGoodsVO = goodsVOList.get(i);
//                if (null == orderGoodsVO) {
//                    continue;
//                }
//                OrderCancelGoodsInfo orderCancelGoodsInfo = new OrderCancelGoodsInfo();
//                orderCancelGoodsInfo.setId(null).setCreateUser(username).setCreateTime(DateUtils.getCurrTime()).setDelFlag(0)
//                        .setOrderNo(backOrderNo).setParentOrderNo(orderNo);
//
//                GoodsInfo goodsInfo = GoodsMemory.getInstance().getGoodsInfo(orderGoodsVO.getGoodsId());
//                if (null == goodsInfo) {
//                    return new BackPriceResultInfo("商品不存在，请核实");
//                }
//
//                if (ValidateUtil.isNotID(goodsInfo.getId())) {
//                    return new BackPriceResultInfo("商品不存在，请核对后再试");
//                }
//                orderCancelGoodsInfo.setGoodsId(goodsInfo.getId());
//                Long specsId = orderGoodsVO.getGoodsSpecsId();
//
//                GoodsSpecs specsInfo = null;
//                if (ValidateUtil.isID(specsId)) { //多规格商品
//                    specsInfo = GoodsSpecsMemory.getInstance().getInfo(specsId);
//                    if (null == specsInfo) {
//                        return new BackPriceResultInfo("商品不存在，请核对后再试");
//                    }
//                    orderCancelGoodsInfo.setName(goodsInfo.getName())
//                            .setGoodsSpecsId(specsInfo.getId())
//                            .setSpecs(specsInfo.getName())
//                            .setDescs(specsInfo.getDescs());
//                    String goodsImage = specsInfo.getImageUrl();
//                    if (ValidateUtil.isNull(goodsImage)) {
//                        //为空时使用商品的头像
//                        goodsImage = goodsInfo.getImageUrl();
//                    }
//                    if (ValidateUtil.isNotNull(goodsImage) && ValidateUtil.isNetUrl(goodsImage)) {
//                        goodsImage = goodsImage.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
//                    }
//                    orderCancelGoodsInfo.setImageUrl(goodsImage);
//                    orderCancelGoodsInfo.setPacketPrice(specsInfo.getPacketPrice()).setGoodsPrice(specsInfo.getPrice());
//                } else { //普通商品
//                    orderCancelGoodsInfo.setName(goodsInfo.getName())
//                            .setDescs(goodsInfo.getDescs())
//                            .setUpc(goodsInfo.getUpc()).setGoodsSpecsId(0L);
//                    String goodsImage = goodsInfo.getImageUrl();
//                    if (ValidateUtil.isNetUrl(goodsImage)) {
//                        goodsImage = goodsImage.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
//                    }
//                    orderCancelGoodsInfo.setImageUrl(goodsImage);
//                    orderCancelGoodsInfo.setPacketPrice(goodsInfo.getPacketPrice()).setGoodsPrice(goodsInfo.getPrice());
//                }
//                orderCancelGoodsInfo.setShopId(goodsInfo.getShopId());
//                orderCancelGoodsInfo.setIsBackApply(REFUND_APPLY_STATUS.APPLY);
//                orderCancelGoodsInfo.setBackTotalCount(orderGoodsVO.getTotalCount());
//                orderCancelGoodsInfo.setBackTotalGoodsPrice(JYMathDoubleUtils.mul(orderCancelGoodsInfo.getBackTotalCount() == null ? 0 : orderCancelGoodsInfo.getBackTotalCount(), orderCancelGoodsInfo.getGoodsPrice()));
//                orderCancelGoodsInfo.setBackTotalPacketPrice(JYMathDoubleUtils.mul(orderCancelGoodsInfo.getBackTotalCount() == null ? 0 : orderCancelGoodsInfo.getBackTotalCount(), orderCancelGoodsInfo.getPacketPrice()));
//                orderCancelGoodsInfo.setBackTotalMoney(JYMathDoubleUtils.add(orderCancelGoodsInfo.getBackTotalGoodsPrice(), orderCancelGoodsInfo.getBackTotalPacketPrice()));
//                try {
//                    UserDaoSql.getInstance().insertObj(PojoTables.ORDER_CANCEL_GOODS_INFO, orderCancelGoodsInfo);
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                    return new BackPriceResultInfo("存储退还商品信息失败，请稍后重试");
//                }
//            }
//        }
        return backPriceResultInfo;
    }

    // 部分商品退款 -活动信息监测
    public static BackPriceResultInfo doBackGames(OrderInfo orderInfo, BackPriceResultInfo resultInfo, String
            orderNo) {
        List<OrderGameRules> orderGameRules = OrderGameMemory.getInstance().listOfOrderNo(orderNo);
        if (ValidateUtil.isAbsList(orderGameRules)) {
            resultInfo = OrderMan.doBackGames(orderInfo, orderGameRules, resultInfo);
            if (resultInfo == null) {
                return new BackPriceResultInfo("申请失败，请稍后重试");
            }
            if (!resultInfo.isSuccess()) {
                return resultInfo.setSuccess(false);
            }
            // 验证成功
        } else {
            // 沒有参与活动信息
        }
        return resultInfo;
    }


    public static BackPriceResultInfo doBackGames(OrderInfo
                                                          orderInfo, List<OrderGameRules> list, BackPriceResultInfo resultInfo) {
        if (ValidateUtil.isNull(orderInfo)) {
            return resultInfo.setError("订单信息不能为空").setSuccess(false);
        }
        if (!ValidateUtil.isAbsList(list)) {
            return resultInfo.setError("活动信息不能为空").setSuccess(false);
        }
        if (!ValidateUtil.isAbsDouble(resultInfo.getBackTotalPrice())) {
            return resultInfo.setError("退款信息不能为空").setSuccess(false);
        }
        Double backTotalPrice = resultInfo.getBackTotalPrice();
        for (OrderGameRules rules : list) {
            if (rules == null) {
                continue;
            }
            if (rules.getGameType() - GAME_TYPE.GOODS == 0
                    || rules.getGameType() - GAME_TYPE.MONEY == 0
                    || rules.getGameType() - GAME_TYPE.FIRST_GOODS == 0
                    || rules.getGameType() - GAME_TYPE.FIRST_MONEY == 0) {
                // 有活动信息暂时先不让其部分商品退款
                Double rang = rules.getRang();
                if (!ValidateUtil.isAbsDouble(rang)) {
                    return resultInfo.setError("活动信息有误").setSuccess(false);
//                    return new ResultInfo("活动信息有误");
                } else {
//                    if (rang <= JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), resultInfo.getBackTotalPrice())) {
                    // 总金额 - 已经 退还或者退还中的金额 - 本地退换的金额
                    if (rang <= JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), resultInfo.getAlreadyApplyMoney()), resultInfo.getBackTotalPrice())) {
                        // 还满足活动信息
                    } else {
                        if (rules.getGameType() - GAME_TYPE.GOODS == 0
                                || rules.getGameType() - GAME_TYPE.FIRST_GOODS == 0) {
                            return resultInfo.setError("退部分商品后，不满足满赠活动").setSuccess(false);
                        } else {
                            backTotalPrice = JYMathDoubleUtils.sub(backTotalPrice, ValidateUtil.isAbsDouble(rules.getAward()) ? rules.getAward() : 0.0d);
                            if (backTotalPrice < 0.0d) {
                                return resultInfo.setError("退款后不符合活动信息,无法退款").setSuccess(false);
                            }
                        }
//                        // 退部分商品后无法满足活动信息
//                        return new ResultInfo("退部分商品后，不满足活动信息");
                    }
                }
            } else if (rules.getGameType() - GAME_TYPE.RED_PACKET_FIRST_GOODS == 0
                    || rules.getGameType() - GAME_TYPE.RED_PACKET_FIRST_MONEY == 0
                    || rules.getGameType() - GAME_TYPE.RED_PACKET_GOODS == 0
                    || rules.getGameType() - GAME_TYPE.RED_PACKET_MONEY == 0) {
                // 红包信息
                Double rang = rules.getRang();
                if (!ValidateUtil.isAbsDouble(rang)) {
                    return resultInfo.setError("活动信息有误").setSuccess(false);
                } else {
                    if (rang <= JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), resultInfo.getAlreadyApplyMoney()), resultInfo.getBackTotalPrice())) {
//                    if (rang <= JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), backTotalPrice)) {
                        // 还满足活动信息
                    } else {
                        // 送商品就不行了啊
                        if (rules.getGameType() - GAME_TYPE.RED_PACKET_FIRST_GOODS == 0
                                || rules.getGameType() - GAME_TYPE.RED_PACKET_GOODS == 0) {
                            return resultInfo.setError("退部分商品后，不满足满赠活动").setSuccess(false);
                        } else {
                            backTotalPrice = JYMathDoubleUtils.sub(backTotalPrice, ValidateUtil.isAbsDouble(rules.getAward()) ? rules.getAward() : 0.0d);
                            if (backTotalPrice < 0.0d) {
                                return resultInfo.setError("退款后不符合活动信息,无法退款").setSuccess(false);
                            }
                        }
                        // 退部分商品后无法满足活动信息
//                        return new ResultInfo("退部分商品后，不满足红包使用金额");
                    }
                }
            }
        }
        resultInfo.setBackTotalPrice(backTotalPrice);
        return resultInfo;
    }

    // 部分商品退款 - 运费检测
    public static BackPriceResultInfo doBackFreeYunFei(ShopInfo shopInfo, OrderInfo orderInfo, Double
            backTotalPrice, BackPriceResultInfo resultInfo) {
        Double backTotalPrice2 = resultInfo.getBackTotalPrice();
        if (ValidateUtil.isAbsDouble(orderInfo.getOriginalYunFei()) && orderInfo.getOriginalYunFei() > 0) {
//            if (JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), backTotalPrice) >= (shopInfo.getFreeYunFei() == null ? 0.0d : shopInfo.getFreeYunFei())) {
            if (JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), backTotalPrice), resultInfo.getAlreadyApplyMoney()) >= (shopInfo.getFreeYunFei() == null ? 0.0d : shopInfo.getFreeYunFei())) {

            } else {
//                JYFileUtils.getFile()
                backTotalPrice2 = JYMathDoubleUtils.sub(backTotalPrice2, orderInfo.getOriginalYunFei());
                if (backTotalPrice2 < 0.0d) {
                    return resultInfo.setSuccess(false).setError("退款后加上配送费不满足退款条件");
                }
            }
            return resultInfo.setBackTotalPrice(backTotalPrice2);
        }
//        if (ValidateUtil.isAbsDouble(shopInfo.getFreeYunFei())) {
//            if (JYMathDoubleUtils.sub(orderInfo.getTotalGoodsMoney(), backTotalPrice) >= shopInfo.getFreeYunFei()) {
//
//            } else {
//                backTotalPrice2 = JYMathDoubleUtils.sub(backTotalPrice2,ValidateUtil.isAbsDouble())
//
//                return new ResultInfo("退还部分商品后不满足店铺减配送费");
//            }
//        } else {
//            // 永远不减免配送费
//        }
        return resultInfo;
    }

    private static OrderGoods getOrderGoodsByOrderNOAndId(String orderNo, Long orderGoodsId) {
        if (ValidateUtil.isNull(orderNo)
                || ValidateUtil.isNotID(orderGoodsId)) {
            return null;
        }
        List<OrderGoods> orderGoodsList = OrderGoodsMemory.getInstance().listOfOrderNo(orderNo);
        if (ValidateUtil.isAbsList(orderGoodsList)) {
            for (OrderGoods goods : orderGoodsList) {
                if (goods == null) {
                    continue;
                }
                if (goods.getId().longValue() - orderGoodsId == 0) {
                    return goods;
                }
            }
        }
        return null;
    }

    private static List<OrderCancelGoodsInfo> getAlreadyApplyListOrderCancelGoodsByOrderNo(String orderNo, Long
            parentOrderGoodsId) {
        if (ValidateUtil.isNull(orderNo)) {
            return null;
        }
        List<OrderCancelInfo> alreadyApplyList = new ArrayList<>();
        List<OrderCancelInfo> tempList = null;
        // 通过的
        tempList = OrderCancelInfoMemory.getInstance().getOrderCancelInfoByParentOrderNo(orderNo, REFUND_APPLY_STATUS.PASS);
        if (ValidateUtil.isAbsList(tempList)) {
            alreadyApplyList.addAll(tempList);
        }
        tempList = null;
        // 申请中的
        tempList = OrderCancelInfoMemory.getInstance().getOrderCancelInfoByParentOrderNo(orderNo, REFUND_APPLY_STATUS.APPLY);
        if (ValidateUtil.isAbsList(tempList)) {
            alreadyApplyList.addAll(tempList);
        }
        tempList = null;
        if (ValidateUtil.isAbsList(alreadyApplyList)) {
            List<OrderCancelGoodsInfo> list = new ArrayList<>();
            for (OrderCancelInfo info : alreadyApplyList) {
                if (info == null) {
                    continue;
                }
                if (ValidateUtil.isNull(info.getOrderNo())) {
                    continue;
                }
                List<OrderCancelGoodsInfo> cancelGoodsInfoList = OrderCancelGoodsMemory.getInstance().listOfOrderCancelGoodsInfoByOrderNO(info.getOrderNo());
                List<OrderCancelGoodsInfo> temp = getOrderGoodsIdInListOrderCancelGoods(cancelGoodsInfoList, parentOrderGoodsId);
                if (ValidateUtil.isAbsList(temp)) {
                    list.addAll(temp);
                }
            }
            if (ValidateUtil.isAbsList(list)) {
                return list;
            }
        }
        return null;
    }

    private static String getImageUrl(String url) {
        if (ValidateUtil.isNull(url)) {
            return "";
        }
        if (ValidateUtil.isNetUrl(url)) {
            // 网络路径
            String t = "pics";
            if (url.contains(t)) {
                return url.substring(url.indexOf(t));
            }
            return url;
        }
        return url;
    }

    private static List<OrderCancelGoodsInfo> getOrderGoodsIdInListOrderCancelGoods
            (List<OrderCancelGoodsInfo> list, Long parentOrderGoodsId) {
        if (ValidateUtil.isAbsList(list) && ValidateUtil.isID(parentOrderGoodsId)) {
            List<OrderCancelGoodsInfo> tempList = new ArrayList<>();
            for (OrderCancelGoodsInfo info : list) {
                if (info == null) {
                    continue;
                }
                if (ValidateUtil.isNotID(info.getParentOrderGoodsId())) {
                    continue;
                }
                if (info.getParentOrderGoodsId().longValue() - parentOrderGoodsId == 0) {
                    tempList.add(info);
                }
            }
            if (ValidateUtil.isAbsList(tempList)) {
                return tempList;
            }
        }
        return null;
    }

    public static List<OrderCancelGoodsInfoVO> listOfOrderCancelGoodsInfoByBackOrderNo(String backOrderNo) {
        if (ValidateUtil.isNotNull(backOrderNo)) {
            List<OrderCancelGoodsInfo> infoList = OrderCancelGoodsMemory.getInstance().listOfOrderCancelGoodsInfoByOrderNO(backOrderNo);
            if (ValidateUtil.isAbsList(infoList)) {
                List<OrderCancelGoodsInfoVO> list = new ArrayList<>();
                for (OrderCancelGoodsInfo goodsInfo : infoList) {
                    if (goodsInfo == null) {
                        continue;
                    }
                    OrderCancelGoodsInfoVO infoVO = new OrderCancelGoodsInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(goodsInfo, infoVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (ValidateUtil.isNotNull(infoVO.getImageUrl())) {
                        infoVO.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImageUrl());
                    }
                    if (infoVO != null) {
                        list.add(infoVO);
                    }
                }
                if (ValidateUtil.isAbsList(list)) {
                    return list;
                }
            }
        }
        return null;
    }

    public static OrderCancelInfoVO getOrderCancelInfoVO(OrderCancelInfo orderInfo) {
        if (orderInfo == null) {
            return null;
        }
        OrderCancelInfoVO infoVO = new OrderCancelInfoVO();
        try {
            ObjectUtils.copyPropertiesExclude(orderInfo, infoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // 图片处理
        if (ValidateUtil.isNotNull(infoVO.getImage1Url())) {
            if (ValidateUtil.isNotNetUrl(infoVO.getImage1Url())) {
                infoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage1Url());
            }
        }
        if (ValidateUtil.isNotNull(infoVO.getImage2Url())) {
            if (ValidateUtil.isNotNetUrl(infoVO.getImage2Url())) {
                infoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage2Url());
            }
        }
        if (ValidateUtil.isNotNull(infoVO.getImage3Url())) {
            if (ValidateUtil.isNotNetUrl(infoVO.getImage3Url())) {
                infoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage3Url());
            }
        }
        if (ValidateUtil.isNotNull(infoVO.getImage4Url())) {
            if (ValidateUtil.isNotNetUrl(infoVO.getImage4Url())) {
                infoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage4Url());
            }
        }
        List<OrderCancelGoodsInfoVO> tempList = OrderMan.listOfOrderCancelGoodsInfoByBackOrderNo(infoVO.getOrderNo());
        if (ValidateUtil.isAbsList(tempList)) {
            infoVO.setCancelGoodsList(tempList);
        }
        return infoVO;
    }

    public static ResultInfo partCancelOrder(OrderInfo orderInfo, ShopInfo shopInfo, Integer
            orderStatus, String orderNo, String backOrderNo, Double backTotalMoney, Double backTotalGoodsMoney, Double
                                                     backTotalPacketMoney, String username, Boolean refundAliWxPay) {
        // 检测各自承担部分

        backTotalMoney = JYMathDoubleUtils.add(backTotalGoodsMoney, backTotalPacketMoney);
        // 1.商家
        Double shopRate = 0d;
        Double shopMoney = 0d;
        // 2. 配送员
        Double postmanRate = 0.0d;
        Double postmanMoney = 0.0d;


        OrderPayInfo payInfo = OrderPayMemory.getInstance().get(orderNo);
        if (payInfo == null) {
            return new ResultInfo("没有支付流水，请稍后重试");
        }
        OrderCancelInfo orderCancelInfo = OrderCancelInfoMemory.getInstance().get(backOrderNo);
        if (orderCancelInfo == null) {
            return new ResultInfo("取消订单信息不存在");
        }
        //1.店铺分成
        if (null != orderInfo.getOrderType()
                && 0 != ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.HUO_YUN - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) { //跑腿订单
            if (null != shopInfo) {
                shopRate = shopInfo.getMoneyRate();//分配比例
            }
            shopRate = payInfo.getShopRate();
            if (ValidateUtil.isNotAbsDouble(shopRate)) {
                return new ResultInfo("店铺分成比例错误");
            }
            shopMoney = JYMathDoubleUtils.add(shopMoney, JYMathDoubleUtils.mul(backTotalGoodsMoney, shopRate));
            if (null != SYS_SETTINGS.SHARE_SHOP_PACKET_MONEY && 0 == 1 - SYS_SETTINGS.SHARE_SHOP_PACKET_MONEY) {
                // 参与分成的话
                shopMoney = JYMathDoubleUtils.add(shopMoney, JYMathDoubleUtils.mul(backTotalPacketMoney, shopRate));
            } else {
                shopMoney = JYMathDoubleUtils.add(shopMoney, backTotalPacketMoney);
            }
        }

        //2. 配送员部分
        if (0 == orderInfo.getIsZiQu()) { //配送的订单才进来
            if (null == SYS_SETTINGS.POSTMAN_SHARE_MONEY) {
                System.out.println("未设置配送员是否参与分成");
                return new ResultInfo("操作失败，请稍后再试。4");
            }
            //如果店铺是自配送的  则无需再处理配送费部分
            if ((null != shopInfo && null != shopInfo.getIsSelfPost() && 0 != 1 - shopInfo.getIsSelfPost())//平台配送
                    || (null != orderInfo.getOrderType() && (0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType() || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType() || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType() || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType()))//跑腿代购帮办
            ) {
                Integer postManShare = SYS_SETTINGS.POSTMAN_SHARE_MONEY; //配送员分成类型（0不参与，1总金额，2参与配送费部分）
                if (postManShare != null && postManShare == SysSettingValueKey.POSTMAN_SHARE_ALL) {
                    postmanRate = payInfo.getPostmanRate();
                    if (ValidateUtil.isAbsDouble(postmanRate)) {
                        postmanMoney = JYMathDoubleUtils.mul(JYMathDoubleUtils.add(backTotalGoodsMoney, backTotalPacketMoney), postmanRate);
                    }
                }
            }
        }
        //3. 业务员分成
        Double businessRate = 0d; //业务员分成比例
        Double businessMoney = 0d;//业务员分成金额
        //获取店铺的业务员
        if (ValidateUtil.isID(orderInfo.getShopId())) {
            String managerUsername = ShopManagerRelationMemory.getInstance().getManagerByShopId(orderInfo.getShopId());
            UserInfo managerInfo = UserInfoMemory.getInstance().getUserInfo(managerUsername);
            if (null != managerInfo && ValidateUtil.isAbsDouble(managerInfo.getRate())) {
                businessRate = payInfo.getBusinessRate();
                //分成支付金额部分
                businessMoney = JYMathDoubleUtils.mul(JYMathDoubleUtils.add(backTotalGoodsMoney, backTotalPacketMoney), JYMathDoubleUtils.div(businessRate, 100));//分配金额
            }
        }
        //4. 城代、平台分成
        String cityAdminUsername = null; //城代账号
        Double cityAdminRate = 0d; //城代分成比例
        Double cityAdminMoney = 0d;//城代分成金额
        Double platformRate = 0d;//平台分成比例
        Double platformMoney = 0d;//平台分成金额
        if (null != SYS_SETTINGS.IS_SYS_CITY_ADMIN_SHARE_MONEY && 0 == 1 - SYS_SETTINGS.IS_SYS_CITY_ADMIN_SHARE_MONEY) { //城代参与分成
//            ResultInfo resultInfo = OrderPay.getPlateShareCityAdminRate(orderInfo.getAgentId(), orderInfo.getShopId(), orderInfo.getShopCity());//平台抽取代理分成比例
//            if (null != resultInfo && resultInfo.isSuccess()) {
//                platformRate = (Double) resultInfo.getObj();
//                if (ValidateUtil.isNotAbsDouble(platformRate)) {
//                    platformRate = 100d;
//                }
//                cityAdminUsername = resultInfo.getMessage();
//            } else {
            platformRate = payInfo.getPlatformRate();
            cityAdminRate = payInfo.getCityAdminRate();
//            }
//            cityAdminRate = JYMathDoubleUtils.sub(100, platformRate);
            switch (SYS_SETTINGS.PLAT_SHARE_CITY_ADMIN_MONEY_TYPE) {//平台抽取城代方式
                case PLAT_SHARE_CITY_ADMIN_MONEY_TYPE.NONE: {//不抽取
                    cityAdminMoney = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(backTotalMoney, postmanMoney), businessMoney), shopMoney);
                }
                break;
                case PLAT_SHARE_CITY_ADMIN_MONEY_TYPE.TOTAL_MONEY: {//抽取订单总金额部分
                    platformMoney = JYMathDoubleUtils.mul(backTotalMoney, platformRate);
                    cityAdminMoney = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(backTotalMoney, shopMoney), postmanMoney), businessMoney), platformMoney);
                }
                break;
                case PLAT_SHARE_CITY_ADMIN_MONEY_TYPE.DELIVER_MONEY: {//抽取配送费部分
                    cityAdminMoney = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(backTotalMoney, shopMoney), postmanMoney), businessMoney), platformMoney);
                }
                break;
                case PLAT_SHARE_CITY_ADMIN_MONEY_TYPE.PAY_MONEY: {//抽取支付金额部分
                    platformMoney = JYMathDoubleUtils.mul(backTotalMoney, platformRate);
                    // 代理收入 = 支付金额-分成给店铺-分成给配送员-分给业务员-分给平台的-活动减金额
                    cityAdminMoney = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(backTotalMoney, shopMoney), postmanMoney), businessMoney), platformMoney);
                }
                break;
            }
        } else {//城代不参与分成
            //平台收入 = 支付金额-分成给店铺-分成给配送员-分给业务员
            platformMoney = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(backTotalMoney, shopMoney), postmanMoney), businessMoney);  // 平台收入 = 支付金额-分成给店铺-分成给配送员-分给业务员
        }
        // 钱计算完毕

        if (orderStatus == ORDER_STATUS.OVER
                || orderStatus == ORDER_STATUS.POSTMAN_FINISH
                || orderStatus == ORDER_STATUS.SHOP_FINISH) {
            // 已经分成过了
            ResultInfo resultInfo = refundPartDistributeMoney(orderNo, username, orderCancelInfo.getOrderType()
                    , backTotalMoney, shopMoney, postmanMoney, platformMoney);
            if (null != resultInfo && !resultInfo.isSuccess()) {
                System.out.println("部分商品退款失败：" + resultInfo.getError());
            }
        } else {
            // 未分成 订单还在进行中
            // 直接修改pay_info分成信息
            // 店铺
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.OrderPay).append(" set updateUser='").append(username).append("'");
            if (ValidateUtil.isAbsDouble(payInfo.getShopMoney())) {
                if (payInfo.getShopMoney() < shopMoney) {
                    return new ResultInfo("操作失败，请稍后重试V1");
                }
                payInfo.setShopMoney(JYMathDoubleUtils.sub(payInfo.getShopMoney(), shopMoney));
                sql.append(",shopMoney=").append(payInfo.getShopMoney());
            }
            // 骑手
            if (ValidateUtil.isAbsDouble(payInfo.getPostmanMoney()) && ValidateUtil.isAbsDouble(postmanMoney)) {
                if (payInfo.getPostmanMoney() < postmanMoney) {
                    return new ResultInfo("操作失败，请稍后重试V2");
                }
                payInfo.setPostmanMoney(JYMathDoubleUtils.sub(payInfo.getPostmanMoney(), postmanMoney));
                sql.append(",postmanMoney=").append(payInfo.getPostmanMoney());
            }
            // 平台
            if (ValidateUtil.isAbsDouble(payInfo.getPlatformAwardMoney()) && ValidateUtil.isAbsDouble(platformMoney)) {
                payInfo.setPlatformAwardMoney(JYMathDoubleUtils.sub(payInfo.getPlatformAwardMoney(), platformMoney));
                sql.append(",platformAwardMoney=").append(payInfo.getPlatformAwardMoney());
            }
            // 业务员
            if (ValidateUtil.isAbsDouble(payInfo.getBusinessMoney()) && ValidateUtil.isAbsDouble(businessMoney)) {
//                if (payInfo.getBusinessMoney() < businessMoney) {
//                    return new ResultInfo("操作失败，请稍重试V3");
//                }
                payInfo.setBusinessMoney(JYMathDoubleUtils.sub(payInfo.getBusinessMoney(), businessMoney));
                sql.append(",businessMoney=").append(payInfo.getBusinessMoney());
            }
            // 城市代理
            if (ValidateUtil.isAbsDouble(payInfo.getCityAdminMoney()) && ValidateUtil.isAbsDouble(cityAdminMoney)) {
//                if (payInfo.getCityAdminMoney() < cityAdminMoney) {
//                    return new ResultInfo("操作失败，请稍后重试V4");
//                }
                payInfo.setCityAdminMoney(JYMathDoubleUtils.sub(payInfo.getCityAdminMoney(), cityAdminMoney));
                sql.append(",cityAdminMoney=").append(payInfo.getCityAdminMoney());
            }
            sql.append("  where delFlag=0 and orderNo='").append(orderInfo.getOrderNo()).append("'");
//            sql.append(",updateUser='").append(username).append("' where delFlag=0 and orderNo='").append(orderInfo.getOrderNo()).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return new ResultInfo("订单支付信息修改失败");
            }
            // 缓存
            OrderPayMemory.getInstance().modify(orderInfo.getOrderNo());
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderInfo.getOrderNo());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }
        if (ValidateUtil.isAbsInteger(orderInfo.getIsPaid()) && 0 == orderInfo.getIsPaid() - 1) { //已经支付过了  需要退款
            Double refundMoney = backTotalMoney;
            //货币金额转换
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY) {//是否使用主币支付 1使用主币支付 0使用外币支付
                //外币支付需要转换
                //外币汇率
                if (ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {
                    //外币计算
                    refundMoney = JYMathDoubleUtils.mul(SYS_SETTINGS.EXCHANGE_RATE, refundMoney);
                }
            }
            if (refundAliWxPay) {
                boolean isRefundSuccess = false;
                if (PAY_TYPE.WALLET.equalsIgnoreCase(orderInfo.getPayType())) {
                    //余额支付  需要退款
                    UserInfo userinfo = UserInfoMemory.getInstance().getUserInfo(orderInfo.getUsername());
                    if (null == userinfo) {
                        return new ResultInfo("退款失败，请稍后再试[用户不存在]");
                    }
                    //用户余额增加
                    ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderInfo.getUsername(), userinfo.getUserType(), orderInfo.getShopId(), UserWalletMan.REFUND_ADD, backTotalMoney, orderInfo.getAwardMoney(), username);
                    if (null != resultInfo) {
                        if (resultInfo.isSuccess()) {
                            //退款成功
                            isRefundSuccess = true;
                        } else {
                            return new ResultInfo(resultInfo.getError());
                        }
                    } else {
                        return new ResultInfo("退款失败，请稍后再试[更新用户余额错误]");
                    }
                } else {
                    if (refundMoney == 0.0d) {
                        isRefundSuccess = OrderPay.savePartRefundOrderCode(backOrderNo, backOrderNo, orderInfo.getPayType());
                    } else {
                        isRefundSuccess = OrderPay.refundPart(orderInfo.getAgentId(), orderInfo.getPayTypeFlag(),
                                orderInfo.getPayType(), orderInfo.getOrderNo(), backOrderNo, orderInfo.getTotalPrice(), refundMoney, orderInfo.getChargeId(), false);
                    }
//                    isRefundSuccess = OrderPay.refund(orderInfo.getPayType(), orderInfo.getOrderNo(), refundMoney, orderInfo.getChargeId());
//                    isRefundSuccess = OrderPay.refundPart(orderInfo.getPayType(), orderInfo.getOrderNo(), backOrderNo, orderInfo.getTotalPrice(), refundMoney, orderInfo.getChargeId());
                }
                if (isRefundSuccess) {
                    //退款成功了
                } else {
                    return new ResultInfo("退款失败，请稍后再试");
                }
            }
        } else {
        }
        // 修改 退款订单信息
        StringBuffer updateSql = new StringBuffer();
        updateSql.append("update ").append(PojoTables.ORDER_CANCEL_INFO).append(" set isPartCancelApply = ").append(REFUND_APPLY_STATUS.PASS)
                .append(",agreeBackTime=").append(DateUtils.getCurrTime()).append(",fcBackTotalMoney = ").append(backTotalMoney)
                .append(",fcBackTotalGoodsMoney=").append(backTotalGoodsMoney).append(",fcBackTotalPacketMoney=").append(backTotalPacketMoney)
        ;
        if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//是否使用主币支付 1使用主币支付 0使用外币支付
            updateSql.append(",exchangeRate=").append(SYS_SETTINGS.EXCHANGE_RATE)
                    .append(",fcTotalPrice=").append(JYMathDoubleUtils.mul(backTotalMoney, SYS_SETTINGS.EXCHANGE_RATE));
        }
        updateSql.append(",updateUser='").append(username).append("'")
                .append(" where orderNo='").append(backOrderNo).append("'");
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.OrderInfo).append(" set isPartCancelApply=").append(REFUND_APPLY_STATUS.PASS)
                .append(" ,updateUser='").append(username).append("'")
                .append(" where orderNo ='").append(orderNo).append("' and delFlag =0");
        try {
            UserDaoSql.getInstance().executeBySql(updateSql.toString());
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("订单修改失败");
        }
        // 添加一种状态  但仅仅的状态
        Long tim = DateUtils.getCurrTime();
        OrderStatus status = new OrderStatus(orderNo, ORDER_STATUS.PAYED_PASS_PART_CANCEL, username, tim);
//        status.setNote(orderCancelInfoVO.getReBackReason());
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, status);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        OrderCancelInfoMemory.getInstance().modify(backOrderNo);
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        // 更新订单状态
        OrderStatusMemory.getInstance().addStatus(orderNo);
        // 处理一下原订单商品相关信息
        dealBackOrderGoodsCount(orderNo, backOrderNo, username);
        return new ResultInfo();
    }

    // todo : 处理一下部分退款后 原订单商品信息
    private static void dealBackOrderGoodsCount(String orderNo, String backOrderNo, String opUser) {
        if (ValidateUtil.isNull(orderNo) || ValidateUtil.isNull(backOrderNo)) {
            System.out.println("订单商品部分退款后~,单号为空~处理失败");
            return;
        }
        OrderCancelInfo cancelInfo = OrderCancelInfoMemory.getInstance().get(backOrderNo);
        if (cancelInfo == null) {
            return;
        }
        List<OrderCancelGoodsInfo> orderCancelGoodsInfos = OrderCancelGoodsMemory.getInstance().listOfOrderCancelGoodsInfoByOrderNO(backOrderNo);
        Set<Long> parentOrderGoodsIdSet = new HashSet<>();
        if (ValidateUtil.isAbsList(orderCancelGoodsInfos)) {
            parentOrderGoodsIdSet = orderCancelGoodsInfos.stream().filter(b -> ValidateUtil.isID(b.getParentOrderGoodsId())).map(b -> b.getParentOrderGoodsId()).collect(Collectors.toSet());
            // Map<Long, Long> collect = orderCancelGoodsInfos.stream().filter(b -> ValidateUtil.isID(b.getParentOrderGoodsId())).collect(Collectors.toMap(OrderCancelGoodsInfo::getId, OrderCancelGoodsInfo::getParentOrderGoodsId, (b, b1) -> b1));
        }
        if (parentOrderGoodsIdSet == null || parentOrderGoodsIdSet.isEmpty()) {
            return;
        }
        Map<Long, Integer> orderCountMap = getOrderGoodsCancelCounts(orderNo, parentOrderGoodsIdSet);
        if (orderCountMap != null && !orderCountMap.isEmpty()) {
            for (Long key : orderCountMap.keySet()) {
                Integer count = orderCountMap.get(key);
                if (count == null || count == 0) {
                    continue;
                }
                StringBuffer sql = new StringBuffer();
                sql.append(" update ").append(PojoTables.OrderGoods)
                        .append(" set  backTotalCount = ").append(count)
                        .append(" , updateUser ='").append(opUser).append("'")
                        .append(" where id = ").append(key)
                        .append(" and orderNo ='").append(orderNo).append("'")
                        .append(" and delFlag = 0").append(" and totalCount >= ").append(count);
                try {
                    UserDaoSql.getInstance().executeBySql(sql.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 更新缓存
        OrderGoodsMemory.getInstance().modifyOrDelGoods(orderNo);
    }

    // 获取当前订单下相关的商品整合信息
    public static Map<Long, Integer> getOrderGoodsCancelCounts(String orderNo, final Set<Long> orderGoodsIdSet) {
        if (ValidateUtil.isNull(orderNo) || (orderGoodsIdSet == null || orderGoodsIdSet.isEmpty())) {
            return Collections.emptyMap();
        }
        List<OrderCancelInfo> orderCancelInfoList = OrderCancelInfoMemory.getInstance().getOrderCancelInfoByParentOrderNo(orderNo, REFUND_APPLY_STATUS.PASS);
        if (!ValidateUtil.isAbsList(orderCancelInfoList)) {
            return Collections.emptyMap();
        }
        Set<String> orderCancelOrderSet = new HashSet<>();
        List<OrderCancelGoodsInfo> orderGoodsList = new ArrayList<>();
        for (OrderCancelInfo info : orderCancelInfoList) {
            if (info == null) {
                continue;
            }
            if (orderCancelOrderSet.contains(info.getOrderNo())) {
                continue;
            }
            orderCancelOrderSet.add(info.getOrderNo());
            List<OrderCancelGoodsInfo> orderCancelGoodsInfos = OrderCancelGoodsMemory.getInstance().listOfOrderCancelGoodsInfoByOrderNO(info.getOrderNo());
            if (ValidateUtil.isAbsList(orderCancelGoodsInfos)) {
                List<OrderCancelGoodsInfo> cancelGoodsInfos = orderCancelGoodsInfos.stream().filter(b -> ValidateUtil.isID(b.getParentOrderGoodsId()) && orderGoodsIdSet.contains(b.getParentOrderGoodsId())).collect(Collectors.toList());
                if (ValidateUtil.isAbsList(cancelGoodsInfos)) {
                    orderGoodsList.addAll(cancelGoodsInfos);
                }
            }
        }
        if (!ValidateUtil.isAbsList(orderGoodsList)) {
            return Collections.emptyMap();
        }
        return orderGoodsList.stream().map(b -> {
            if (b.getBackTotalCount() == null) {
                b.setBackTotalCount(0);
            }
            return b;
        }).collect(Collectors.groupingBy(OrderCancelGoodsInfo::getParentOrderGoodsId, Collectors.summingInt(OrderCancelGoodsInfo::getBackTotalCount)));
    }

    //退还商品，退还订单金额
    public static ResultInfo refundPartDistributeMoney(String orderNo, String opUsername, Integer
            orderType, Double backTotalMoney, Double shopMoney, Double postmanMoney, Double platformMoney) {
        if (ValidateUtil.isNull(orderNo)) {
            return new ResultInfo("订单信息有误");
        }

        OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderNo);
        if (null == orderPayInfo) {
            return new ResultInfo("订单信息有误.");
        }

        //是否已经退过一次了
        if (0 == 1 - orderPayInfo.getIsOrderCancel()) {
            return new ResultInfo("已经全部退款了");
        }

        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.OrderPay).append(" set ")
                .append(" updateUser ='").append(opUsername).append("' ");
        //1. 店铺
        if (ValidateUtil.isNotNull(orderPayInfo.getSeller())) {
            UserWallet wallet = UserWalletMemory.getInstance().getWallet(orderPayInfo.getSeller());
            if (wallet.getMoney() < shopMoney) {
                return new ResultInfo("店铺余额不足，无法退款");
            }
            Double shopRate = orderPayInfo.getShopRate();//分成比例
//            Double shopMoney = orderPayInfo.getShopMoney();//分成金额
            UserWalletFlow shopFlow = new UserWalletFlow(orderPayInfo.getSeller(), UserType.SHOP_OWNER, orderPayInfo.getOrderNo(), orderType, backTotalMoney,
                    shopMoney, shopRate, UserWalletFlowType.FLOW_COST,
                    opUsername, DateUtils.getCurrTime());

            //汇率
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//是否使用主币支付 1使用主币支付 0使用外币支付
                shopFlow.setExchangeRate(SYS_SETTINGS.EXCHANGE_RATE);
                shopFlow.setFcOrderTotalMoney(JYMathDoubleUtils.mul(backTotalMoney, SYS_SETTINGS.EXCHANGE_RATE));
                shopFlow.setFcMoney(JYMathDoubleUtils.mul(shopMoney, SYS_SETTINGS.EXCHANGE_RATE));
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.USER_WALLET_FLOW, shopFlow);//退款 店铺流水
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("创建店铺分配流水失败.");
            }

            //店铺余额减少  v2
            ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(orderPayInfo.getSeller(), UserType.SHOP_OWNER, orderPayInfo.getSellerId(), UserWalletMan.REFUND, shopMoney, 0d, opUsername);
            if (null != resultInfo && !resultInfo.isSuccess()) {
                System.out.println("更新店铺余额错误:" + resultInfo.getError());
            }
            if (JYMathDoubleUtils.sub(orderPayInfo.getShopMoney(), shopMoney) < 0) {
                return new ResultInfo("退还金额不能大于商家分成金额");
            }
            Double shopReal = orderPayInfo.getShopMoney() == null ? 0.0d : orderPayInfo.getShopMoney();
            sql.append(",shopMoney = ").append(JYMathDoubleUtils.sub(shopReal, shopMoney));
        }

        //2. 配送员
        if (ValidateUtil.isNotNull(orderPayInfo.getPostman()) && ValidateUtil.isAbsDouble(postmanMoney)) {
            Double postmanRate = orderPayInfo.getPostmanRate();
//            Double postmanMoney = orderPayInfo.getPostmanMoney();
            UserWalletFlow postmanFlow = new UserWalletFlow(orderPayInfo.getPostman(), UserType.POSTMAN, orderNo, orderType, backTotalMoney,
                    postmanMoney, postmanRate, UserWalletFlowType.FLOW_COST,
                    opUsername, DateUtils.getCurrTime());
            //汇率
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//是否使用主币支付 1使用主币支付 0使用外币支付
                postmanFlow.setExchangeRate(SYS_SETTINGS.EXCHANGE_RATE);
                postmanFlow.setFcOrderTotalMoney(JYMathDoubleUtils.mul(backTotalMoney, SYS_SETTINGS.EXCHANGE_RATE));
                postmanFlow.setFcMoney(JYMathDoubleUtils.mul(postmanMoney, SYS_SETTINGS.EXCHANGE_RATE));
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.USER_WALLET_FLOW, postmanFlow);//退款 配送流水
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("创建配送员分配流水失败.");
            }

            if (ValidateUtil.isAbsDouble(postmanMoney)) {
                //配送员余额减少
                ResultInfo resultInfoPostMan = UserWalletMan.saveOrUpdateUserWallet(orderPayInfo.getPostman(), UserType.POSTMAN, null, UserWalletMan.REFUND, postmanMoney, 0d, opUsername);
                if (null != resultInfoPostMan && !resultInfoPostMan.isSuccess()) {
                    System.out.println("更新配送员余额错误:" + resultInfoPostMan.getError());
                }
            }

            Double postReal = orderPayInfo.getPostmanMoney() == null ? 0.0d : orderPayInfo.getPostmanMoney();
            if (JYMathDoubleUtils.sub(postReal, postmanMoney) < 0) {
                return new ResultInfo("退还金额不能大于骑手分成金额");
            }
            sql.append(",postmanMoney = ").append(JYMathDoubleUtils.sub(postReal, postmanMoney));
        }


        //3. 平台
        if (ValidateUtil.isAbsDouble(platformMoney)) {
            Double platformRate = orderPayInfo.getPlatformRate();
//        Double platformMoney = orderPayInfo.getPlatformMoney();
            UserWalletFlow systemFlow = new UserWalletFlow("admin", UserType.SUPER_ADMIN, orderNo, orderType, backTotalMoney,
                    platformMoney, platformRate, UserWalletFlowType.FLOW_COST,
                    opUsername, DateUtils.getCurrTime());
            //汇率
            if (null != SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && 0 == SYS_SETTINGS.USE_MAIN_CURRENCY_PAY && ValidateUtil.isAbsDouble(SYS_SETTINGS.EXCHANGE_RATE)) {//是否使用主币支付 1使用主币支付 0使用外币支付
                systemFlow.setExchangeRate(SYS_SETTINGS.EXCHANGE_RATE);
                systemFlow.setFcOrderTotalMoney(JYMathDoubleUtils.mul(backTotalMoney, SYS_SETTINGS.EXCHANGE_RATE));
                systemFlow.setFcMoney(JYMathDoubleUtils.mul(platformMoney, SYS_SETTINGS.EXCHANGE_RATE));
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.USER_WALLET_FLOW, systemFlow);//退款 平台流水
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("创建系统分配流水失败.");
            }
            Double plateReal = orderPayInfo.getPlatformMoney() == null ? 0.0d : orderPayInfo.getPlatformMoney();
            if (JYMathDoubleUtils.sub(plateReal, platformMoney) < 0) {
                return new ResultInfo("退还金额不能大于骑手分成金额");
            }
            sql.append(",shopMoney = ").append(JYMathDoubleUtils.sub(plateReal, platformMoney));
        }
        try {
            sql.append(" where id = ").append(orderPayInfo.getId());
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("退款后，修改分成失败");
        }
        OrderPayMemory.getInstance().modify(orderPayInfo.getOrderNo());
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderPayInfo.getOrderNo());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return new ResultInfo();
    }


    //  *******************************订单取消部分商品结束****************************************


    //---------------------判断是否为聚合订单
    //判断订单编号是聚合订单编号还是普通编号
    public static boolean isMultiOrder(String orderNo) {
        if (ValidateUtil.isNull(orderNo)) {
            return false;
        }
        if ("M".equalsIgnoreCase(orderNo.substring(0, 1))) {
            return true;
        }
        return false;
    }

    //----------------------------
    //给锁匠加积分
    public static boolean postmanScore(OrderInfo orderInfo) {
        if (null == orderInfo) {
            return false;
        }
        Double payMoney = orderInfo.getTotalMoney();
        if (ValidateUtil.isNotAbsDouble(payMoney)) {
            return true;
        }

        if (ValidateUtil.isNull(orderInfo.getPostManUsername())) {
            return false;
        }

        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(orderInfo.getPostManUsername());
        if (null == cityPostman) {
            return false;
        }

        if (null != SYS_SETTINGS.POSTMAN_MONEY_SCORE && SYS_SETTINGS.POSTMAN_MONEY_SCORE > 0) {
            Double score = JYMathDoubleUtils.div(payMoney, SYS_SETTINGS.POSTMAN_MONEY_SCORE, 2);
            score = JYMathDoubleUtils.add(cityPostman.getScore(), score);

            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.CityPostman).append(" set score=").append(score).append(" where username = '").append(orderInfo.getPostManUsername()).append("' and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
            //修改缓存
            CityPostmanMemory.getInstance().modifyByUsername(orderInfo.getPostManUsername());
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_MODIFY).setStr01(orderInfo.getPostManUsername());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }
        return true;
    }


    //分享商品处理
    private static boolean shareGoodsOp(String orderNo, String username, String opUsername) {
        //获取关联表信息
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("orderNo", orderNo);
        query.addCondition(expression);
        String sql = DaoUtils.getSql(PojoTables.SHARE_GOOD_ORDER_RELATION, query);
        ShareGoodOrderRelation shareGoodOrderRelation = null;
        try {
            shareGoodOrderRelation = (ShareGoodOrderRelation) DataDaoSql.getInstance().getObject(ShareGoodOrderRelation.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        if (null == shareGoodOrderRelation) {
            System.out.println("当前订单没有分享者记录：" + orderNo);
            return false;
        }
        //更新关联表成功过标识
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SHARE_GOOD_ORDER_RELATION)
                .append(" set isSuccess=1,updateUser='").append(opUsername).append("' where  delFlag = 0 and orderNo = '")
                .append(orderNo).append("' and username = '").append(username).append("'");
        try {
            DataDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        //查询现在分享情况
        QueryCondition queryShare = QueryCondition.getInstance();
        Expression expressionShare = Expression.getInstance();
        expressionShare.addChild("delFlag", 0);
        expressionShare.addChild("username", shareGoodOrderRelation.getShareUsername());
        expressionShare.addChild("goodsId", shareGoodOrderRelation.getGoodsId());
        queryShare.addCondition(expressionShare);
        String sqlShare = DaoUtils.getSql(PojoTables.SHARE_GOOD_RECORD, queryShare);
        ShareGoodRecord shareGoodRecord = null;
        try {
            shareGoodRecord = (ShareGoodRecord) DataDaoSql.getInstance().getObject(ShareGoodRecord.class, sqlShare);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("获取分享记录失败" + orderNo);
            return false;
        }
        if (null == shareGoodRecord) {
            System.out.println("当前订单无分享记录" + orderNo);
            return false;
        } else {
            if (null == shareGoodRecord.getSuccessNum()) {
                shareGoodRecord.setSuccessNum(0);
            }
            if (null == shareGoodRecord.getNeedNum()) {
                shareGoodRecord.setNeedNum(0);
            }
            if (null == shareGoodRecord.getSuccessNum()) {
                shareGoodRecord.setSuccessNum(0);
            }
            //当前的数量是否可以再增加一条记录
            if (null != SYS_SETTINGS.SHARE_GOODS_CAN_PULL_MULTI && 0 == 1 - SYS_SETTINGS.SHARE_GOODS_CAN_PULL_MULTI) {
                //分享后可领取多个商品
                if (0 == (shareGoodRecord.getSuccessNum() + 1) % shareGoodRecord.getNeedNum() && Math.floor((shareGoodRecord.getSuccessNum() + 1) / shareGoodRecord.getNeedNum()) > shareGoodRecord.getCanPullNum()) {
                    if (!saveSharePullRecord(shareGoodOrderRelation.getShareUsername(), shareGoodRecord)) {
                        return false;
                    }
                }
            } else {
                //分享后，如果够人数只能领取一个商品
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select count(1) as counts from ").append(PojoTables.SHARE_GOOD_PULL_RECORD).append(" where delFlag =0 and shareId = ").append(shareGoodRecord.getId());
                Long count = 0l;
                try {
                    count = DataDaoSql.getInstance().getCount(sbSql.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return false;
                }

                //查询是否已经有了，
                if (ValidateUtil.isNotAbsLong(count)) {
                    // 如果没有的话 则增加一条记录
                    if (!saveSharePullRecord(username, shareGoodRecord)) {
                        return false;
                    }
                }
            }

        }

        //更新领取记录里的购买次数
        StringBuffer sb2 = new StringBuffer();
        sb2.append("update ").append(PojoTables.SHARE_GOOD_RECORD)
                .append(" set successNum=successNum+1,updateUser='").append(opUsername).append("',canPullNum=").append(shareGoodRecord.getCanPullNum()).append("  where  delFlag = 0 and goodsId = ")
                .append(shareGoodOrderRelation.getGoodsId()).append(" and username = '").append(shareGoodOrderRelation.getShareUsername()).append("'");
        try {
            DataDaoSql.getInstance().executeBySql(sb2.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }


        return true;
    }

    private static boolean saveSharePullRecord(String username, ShareGoodRecord shareGoodRecord) {
        if (null == shareGoodRecord) {
            return false;
        }
        shareGoodRecord.setCanPullNum(shareGoodRecord.getCanPullNum() + 1);
        //增加一行
        ShareGoodPullRecord shareGoodPullRecord = new ShareGoodPullRecord();
        shareGoodPullRecord.setUsername(username);
        shareGoodPullRecord.setShareId(shareGoodRecord.getId());
        shareGoodPullRecord.setGoodsId(shareGoodRecord.getGoodsId());
        shareGoodPullRecord.setShopId(shareGoodRecord.getShopId());
        shareGoodPullRecord.setGoodsName(shareGoodRecord.getGoodsName());
        shareGoodPullRecord.setGoodsDescs(shareGoodRecord.getGoodsDescs());
        shareGoodPullRecord.setGoodsPrice(shareGoodRecord.getGoodsPrice());
        shareGoodPullRecord.setGoodsOriginalPrice(shareGoodRecord.getGoodsOriginalPrice());
        shareGoodPullRecord.setGoodsImageUrl(shareGoodRecord.getGoodsImageUrl());
        shareGoodPullRecord.setIsPull(0);
        shareGoodPullRecord.setIsOver(0);
        shareGoodPullRecord.setDelFlag(0);
        shareGoodPullRecord.setCreateTime(DateUtils.getCurrTime());
        try {
            DataDaoSql.getInstance().insertObj(PojoTables.SHARE_GOOD_PULL_RECORD, shareGoodPullRecord);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }



    // 用户判断订单是不是在进行中
    public static boolean userOrderIsIng(OrderInfo order) {
        if (order == null) {
            return false;
        }
        if (order.getOrderStatus() != ORDER_STATUS.CANCEL_BY_SYSTEM
                && order.getOrderStatus() != ORDER_STATUS.CANCEL
                && order.getOrderStatus() != ORDER_STATUS.OVER
                && (order.getIsRefundApply() != null
                && order.getIsRefundApply() != REFUND_APPLY_STATUS.PASS)
                && order.getOrderStatus() != ORDER_STATUS.PAYED_CANCEL) {
            return true;
        }
        return false;
    }


    // **二级骑手相关****************************************************
    // 判断 是否二级骑手未抢单
    public static boolean isUnSecondaryDelivery(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return false;
        } else {
            Long shopId = orderInfo.getShopId();
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
            if (shopInfo == null) {
                return false;
            }
            if (orderInfo.getOrderType() == ORDER_TYPE.SHOP_GOODS // 购物的
                    && ValidateUtil.isNull(orderInfo.getSecondaryPostManUsername())
                    && isUnSecondaryDeliverys(orderInfo) // 检测订单的状态等
            ) {
                return true;
            }
        }
        return false;
    }

    // 根据订单的状态判断订单是属于哪种类行的    进而根据状态判断该订单是否为可抢状态
    private static boolean isUnSecondaryDeliverys(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return false;
        }
        if (orderInfo.getIsSeriesSaleShop() == SHOP_SERIESSALE_TYPE.SERIESSALE_NO) {
            // 其他系统的商家暂时先不考虑
            return false;
        } else if (orderInfo.getIsSeriesSaleShop() == SHOP_SERIESSALE_TYPE.SERIESSALE_SHOP) { // 校外商家
            if (
                    (orderInfo.getShopSelfPost() == 1
                            && (ValidateUtil.isNull(orderInfo.getSecondaryPostManUsername()))
                            && (orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_SURE // 店铺抢单
                            || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_READY // 店铺备货完成
                            || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS // 店铺已发货
                            || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT //送达提货点 // reCancel 2019-8-24 吃啥需要看到
                    )
                    ) // 自配送
                            || ((orderInfo.getShopSelfPost() == 0)
                            && (ValidateUtil.isNull(orderInfo.getSecondaryPostManUsername()))
                            && (orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_READY // 店铺备货完成
                            || orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS // 店铺已发货
                            || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT //送达提货点 // reCancel 2019-8-24 吃啥需要看到
                            || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE //配送员接单
                            || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN //配送员到店
                            || orderInfo.getOrderStatus() == ORDER_STATUS.PEISONG //在路上
                            || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS // 已取货
                    )
                    )
            ) {
                return true;
            }
        } else if (orderInfo.getIsSeriesSaleShop() == SHOP_SERIESSALE_TYPE.INNER_SHOP) { // 校内商家
            if ((orderInfo.getShopSelfPost() != null && orderInfo.getShopSelfPost() == 0)
                    && (
                    orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_SURE // 店铺抢单
            )) { // 校内商家订单 自配送
                return true;
            } else { // 自配送订单
                return false;
            }
        }
        return false;
    }

    // -------------聚合订单 ----------------骑手-------------

    // 骑手抢聚合订单
    public static ResultInfo postmanSureMultipleOrder(OrderInfo orderInfo, Long companyId, String orderNo, int
            oStatus, String codeSnippet, UserInfo user, String opUser) {
        if (ValidateUtil.isNull(orderNo)) {
            return new ResultInfo("请选择聚合订单");
        }
        if (ValidateUtil.isNull(opUser)) {
            opUser = user.getUsername();
        }
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Long time = DateUtils.getCurrTime();
        String postmanPhone = user.getTelPhone();
        if (ValidateUtil.isNull(postmanPhone)) {
            postmanPhone = user.getUsername();
        }
        String poto = user.getSignPhoto();
        HashSet<String> orderSet = OrderInfoMemory.getInstance().listOfParentOrderNo(orderNo);
        if (orderSet == null) {
            orderSet = new HashSet<>();
        }
        orderSet.add(orderNo);
        for (String ono : orderSet) {
            StringBuilder sb = new StringBuilder();
            if (OrderMan.isMultipleSonOrder(ono)) {
                //直接生成配送验证码，去提货
                //生成取货验证码
                String verifyCode = OrderMan.getVerifyCode();
                if (ValidateUtil.isNull(verifyCode)) {
                    UserDaoSql.getInstance().rollback(conn);
                    return new ResultInfo("生成验证码失败，请稍后再试");
                }
                sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(oStatus)
                        .append(",verifyCode='").append(verifyCode).append("',updateUser='").append(opUser).append("',postmanUsername='")
                        .append(user.getUsername()).append("',postmanName='").append(user.getName()).append("',postmanPhone='").append(postmanPhone)
                        .append("',postmanImageUrl='").append(poto).append("',postmanSureTime=").append(time)
                        .append(ValidateUtil.isNull(codeSnippet) ? "" : codeSnippet)
                        .append(" where delFlag=0 and orderNo = '").append(ono).append("'");
            } else {
                sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(oStatus)
                        .append(",updateUser='").append(opUser).append("',postmanUsername='")
                        .append(user.getUsername()).append("',postmanName='").append(user.getName()).append("',postmanPhone='").append(postmanPhone)
                        .append("',postmanImageUrl='").append(poto).append("',postmanSureTime=").append(time);
                if (ValidateUtil.isID(companyId)) {
                    sb.append(", grabCompanyId = ").append(companyId);
                }
                sb.append(ValidateUtil.isNull(codeSnippet) ? "" : codeSnippet).append(" where delFlag=0 and orderNo = '").append(ono).append("'");

            }
            OrderStatus orderStatus = new OrderStatus(ono, oStatus, opUser, time);
            try {
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus, conn);
                UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
            } catch (SQLException e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                UserDaoSql.getInstance().close(conn);
                return new ResultInfo("操作失败，请稍后重试");
            }
        }
        try {
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 更新缓存
        for (String ono : orderSet) {
            //订单状态缓存
            OrderStatusMemory.getInstance().addStatus(ono);
            //修改缓存
            OrderInfoMemory.getInstance().modifyStatus(ono);
        }
        // 发送极光推送
        Notice.publishNotice2Person(orderInfo.getSysAppKey(), orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待");
        return new ResultInfo();
    }


    // 一乙项目获取
    public static boolean postmanArriveShopMultipleOrder(String opUser, String updateTimeStr, OrderInfo
            orderInfo) throws Exception {
        if (!OrderMan.isMultipleSonOrder(orderInfo)) {
            throw new Exception("请选择聚合订单编号");
        }
        if (ValidateUtil.isNull(updateTimeStr)) {
            updateTimeStr = "";
        }
        // 子订单  首先看父类订单是不是取货中
        if (ValidateUtil.isNull(orderInfo.getParentOrderNo())) {
            System.out.println("聚合子订单信息有误" + orderInfo.getOrderNo());
            throw new Exception("订单信息有误");
        }
        OrderInfo parentInfo = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getParentOrderNo());
        if (parentInfo == null) {
            throw new Exception("聚合父订单信息为空");
        }
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("数据库连接异常");
        }
        long time = DateUtils.getCurrTime();
        // 1. 先更新父订单
        if (parentInfo.getOrderStatus() != ORDER_STATUS.POSTMAN_DAODIAN) {
            StringBuilder pSql = new StringBuilder();
            pSql.append(" update  ").append(PojoTables.OrderInfo).append(" set UpdateUser ='")
                    .append(opUser).append("'").append(updateTimeStr)
                    .append(",orderStatus =").append(ORDER_STATUS.POSTMAN_DAODIAN)
                    .append(" where orderNo ='").append(parentInfo.getOrderNo()).append("' and delFlag = 0");
            OrderStatus status = new OrderStatus(parentInfo.getOrderNo(), ORDER_STATUS.POSTMAN_DAODIAN, opUser, time);
            try {
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, con);
                UserDaoSql.getInstance().executeBySql(pSql.toString(), con);
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(con);
                UserDaoSql.getInstance().close(con);
                throw new Exception("数据库连接异常");
            }
        }
        // 2. 更新子订单
        StringBuilder sSql = new StringBuilder();
        sSql.append(" update  ").append(PojoTables.OrderInfo).append(" set UpdateUser ='")
                .append(opUser).append("'").append(updateTimeStr)
                .append(",orderStatus =").append(ORDER_STATUS.POSTMAN_DAODIAN)
                .append(" where orderNo ='").append(orderInfo.getOrderNo()).append("' and delFlag = 0");
        OrderStatus status = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.POSTMAN_DAODIAN, opUser, time);
        try {
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, con);
            UserDaoSql.getInstance().executeBySql(sSql.toString(), con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            throw new Exception("数据库连接异常");
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        OrderStatusMemory.getInstance().addStatus(orderInfo.getOrderNo());
        if (parentInfo.getOrderStatus() != ORDER_STATUS.POSTMAN_DAODIAN) {
            OrderInfoMemory.getInstance().modifyStatus(parentInfo.getOrderNo());
        }
        return true;
    }

    // 骑手---聚合订单分部取货
    public static synchronized void postmanPullGoodsMultipleOrder(String opUser, String
            updateTimeStr, OrderInfo orderInfo) throws Exception {
        if (!OrderMan.isMultipleSonOrder(orderInfo)) {
            throw new Exception("请选择聚合订单编号");
        }
        if (ValidateUtil.isNull(updateTimeStr)) {
            updateTimeStr = "";
        }
        OrderInfo parentInfo = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getParentOrderNo());
        if (parentInfo == null) {
            throw new Exception("聚合父订单信息为空");
        }
        HashSet<String> set = OrderInfoMemory.getInstance().listOfParentOrderNo(parentInfo.getOrderNo());
        if (set == null || set.isEmpty()) {
            throw new Exception("未获取到子订单");
        }
        boolean isAllPullGoods = true;
        for (String orderNo : set) {
            if (orderInfo.getOrderNo().equals(orderNo)) {
                continue;
            }
            OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (info == null) {
                continue;
            }
            if (info.getOrderStatus() != ORDER_STATUS.POSTMAN_PULL_GOODS) {
                isAllPullGoods = false;
                break;
            }
        }
        Long tim = DateUtils.getCurrTime();
        Connection con = UserDaoSql.getInstance().getConnection(true);
        // 1. 如果是都已经取货了  就取货了
        if (isAllPullGoods) {
            StringBuilder pSql = new StringBuilder();
            pSql.append("update  ").append(PojoTables.OrderInfo).append(" set updateUser ='").append(opUser)
                    .append("'").append(updateTimeStr)
                    .append(",orderStatus = ").append(ORDER_STATUS.POSTMAN_PULL_GOODS)
                    .append(" where delFlag = 0 and orderNo ='").append(parentInfo.getOrderNo()).append("'");

            OrderStatus status = new OrderStatus(parentInfo.getOrderNo(), ORDER_STATUS.POSTMAN_PULL_GOODS, opUser, tim);
            try {
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, con);
                UserDaoSql.getInstance().executeBySql(pSql.toString(), con);
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(con);
                UserDaoSql.getInstance().close(con);
                throw new Exception("操作失败,请稍后重试");
            }
        }
        // 2. 设置子订单已经取货了
        StringBuilder sSql = new StringBuilder();
        sSql.append(" update  ").append(PojoTables.OrderInfo).append(" set UpdateUser ='")
                .append(opUser).append("'").append(updateTimeStr)
                .append(",orderStatus =").append(ORDER_STATUS.POSTMAN_PULL_GOODS)
                .append(" where orderNo ='").append(orderInfo.getOrderNo()).append("' and delFlag = 0");
        OrderStatus status = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.POSTMAN_PULL_GOODS, opUser, tim);
        try {
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, con);
            UserDaoSql.getInstance().executeBySql(sSql.toString(), con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            throw new Exception("操作失败");
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        OrderStatusMemory.getInstance().addStatus(orderInfo.getOrderNo());
        if (isAllPullGoods) {
            OrderStatusMemory.getInstance().addStatus(parentInfo.getOrderNo());
            OrderInfoMemory.getInstance().modifyStatus(parentInfo.getOrderNo());
        }
    }

    // 修改聚合订单的状态
    public static void modifyOrderStatusMultipleOrder(String updateUser, String orderNo, int orderStatus, String
            updateTimeStr, String note) throws Exception {
        if (!OrderMan.isMultipleParentOrder(orderNo)) {
            throw new Exception("请选择聚合订单编号");
        }
        if (ValidateUtil.isNull(updateTimeStr)) {
            updateTimeStr = "";
        }

        HashSet<String> hashSet = OrderInfoMemory.getInstance().listOfParentOrderNo(orderNo);
        if (hashSet == null) {
            hashSet = new HashSet<>();
        }
        hashSet.add(orderNo);

        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
            Long tim = DateUtils.getCurrTime();
            for (String ono : hashSet) {
                StringBuilder sb = new StringBuilder();
                sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(orderStatus)
                        .append(",updateUser='").append(updateUser).append("'").append(updateTimeStr).append(" where delFlag = 0 and orderNo = '").append(ono).append("'");

                OrderStatus status = new OrderStatus(ono, orderStatus, updateUser, tim);
                status.setNote(note);
                UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, conn);
            }
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().close(conn);
            throw e;
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        for (String ono : hashSet) {
            //修改订单信息缓存
            OrderInfoMemory.getInstance().modifyStatus(ono);
            //修改订单状态信息缓存
            OrderStatusMemory.getInstance().addStatus(ono);
        }
    }

    public static void checkMultipleOrderAllShopSure(String updateUser, OrderInfo orderInfo) throws Exception {
        if (!OrderMan.isMultipleSonOrder(orderInfo)) {
            throw new Exception("您选择的订单有误");
        }
        String parentOrderNo = orderInfo.getParentOrderNo();
        if (ValidateUtil.isNull(parentOrderNo)) {
            throw new Exception("订单信息异常");
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(parentOrderNo);
        if (info == null) {
            throw new Exception("获取订单信息错误");
        }
        if (info.getOrderStatus() == ORDER_STATUS.PAYED) {
            HashSet<String> hashSet = OrderInfoMemory.getInstance().listOfParentOrderNo(parentOrderNo);
            boolean isShopSure = false;
            if (hashSet == null) {
                isShopSure = true;
            } else {
                for (String ono : hashSet) {
                    OrderInfo info1 = OrderInfoMemory.getInstance().getOrderInfo(ono);
                    if (info1 == null) {
                        continue;
                    }
                    if (info1.getOrderStatus() == ORDER_STATUS.PAYED
                            || info1.getOrderStatus() == ORDER_STATUS.SHOP_REFUSED
                            || info1.getOrderStatus() == ORDER_STATUS.CANCEL
                            || info1.getOrderStatus() == ORDER_STATUS.PAYED_CANCEL
                            || info1.getOrderStatus() == ORDER_STATUS.CANCEL_BY_SYSTEM) {
                        isShopSure = false;
                    } else {
                        isShopSure = true;
                    }
                }
            }
            if (isShopSure) {
                String shopSureTime = ",shopSureTime=" + DateUtils.getCurrTime();
                if (!OrderMan.modifyOrderStatus(updateUser, parentOrderNo, ORDER_STATUS.SHOP_SURE, shopSureTime)) {
                    throw new Exception("操作失败，请稍后再试");
                }
                OrderInfo parentOrder = OrderInfoMemory.getInstance().getOrderInfo(parentOrderNo);
                if (parentOrder != null) {
                    Long shopId = parentOrder.getSquareShopId();
                    if (ValidateUtil.isNotID(shopId)) {
                        shopId = parentOrder.getShopId();
                    }
                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
                    if (shopInfo != null) {
                        //商户订单量增加
                        ShopMan.addShopOrderCounts(shopInfo.getId(), shopInfo.getOwnUsername(), updateUser);
                    }
                }
            }
        }
    }

    // 转单
    public static ResultInfo changePostman(String orderNo, String fromUsername, String toUsername, String
            opUsername) {
        return changePostman(orderNo, fromUsername, toUsername, opUsername, false);
    }

    //------------------------
    public static ResultInfo changePostman(String orderNo, String fromUsername, String toUsername, String
            opUsername, boolean isSystem) {
        if (ValidateUtil.isNull(orderNo) || ValidateUtil.isNull(fromUsername) || ValidateUtil.isNull(toUsername)) {
            return new ResultInfo("信息不完整，请稍后再试");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return new ResultInfo("订单不存在，请稍后再试");
        }

        String tmpUsername = "";
        if (toUsername.length() < 11) {
            List<CityPostman> list = CityPostmanMemory.getInstance().listOfCity(orderInfo.getShopCity(), 2, null, null, null, null, null, null);
            if (!ValidateUtil.isAbsList(list)) {
                return new ResultInfo("请填写完整的手机号再试");
            }

            for (int i = 0; i < list.size(); i++) {
                if (ValidateUtil.isNotNull(tmpUsername)) {
                    return new ResultInfo("账号不唯一 请输入完整账号");
                }
                CityPostman c = list.get(i);
                if (null == c) {
                    continue;
                }
                String cU = c.getUsername();
                if (ValidateUtil.isNull(cU)) {
                    continue;
                }
                if (toUsername.equalsIgnoreCase(cU.substring(cU.length() - toUsername.length()))) {
                    tmpUsername = cU;
                }
            }
            if (ValidateUtil.isNull(tmpUsername)) {
                return new ResultInfo("未匹配到配送员，请填写完整手机号");
            } else {
                toUsername = tmpUsername;
            }
        }

        //传入的配送员账号可能不准确
        String fromUser = orderInfo.getPostManUsername();
        if (ValidateUtil.isNotNull(fromUser)) {
            fromUsername = fromUser;
        }

        if (fromUsername.equalsIgnoreCase(toUsername)) {
            return new ResultInfo("您不可以将订单转给自己");
        }

        CityPostman fromPostman = CityPostmanMemory.getInstance().getPostman(fromUsername);
        if (null == fromPostman) {
            return new ResultInfo("发起者信息不存在");
        }
        CityPostman toPostman = CityPostmanMemory.getInstance().getPostman(toUsername);
        if (null == toPostman) {
            return new ResultInfo("接受者信息不存在");
        }
        if (0 == toPostman.getIsWork()) {
            return new ResultInfo("对方未上班，无法转单");
        }

        if (toPostman.getPostman_type() != null && toPostman.getPostman_type() == 2) {
            return new ResultInfo("您不可以将订单转给机动骑手");
        }

        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return new ResultInfo("已发起转单，请等待对方操作");
        }
        // 检测是不是服务店铺的那种 如果是  检测提示骑手是否服务当前店铺
        if (SYS_SETTINGS.POSTMAN_SERVICE_SHOP == 1
                && (ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType() == 0 || (orderInfo.getIsShopPaoTuiOrder() == 1 && orderInfo.getOrderType() - ORDER_TYPE.PAO_TUI == 0))) {
            ShopInfo shopInfo = null;
            if (orderInfo.getIsShopPaoTuiOrder() == 1 && orderInfo.getOrderType() - ORDER_TYPE.PAO_TUI == 0) {
                shopInfo = ShopMemory.getInstance().getShopByUsername(orderInfo.getUsername());
            } else {
                shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            }
            if (shopInfo == null) {
                return new ResultInfo("当前店铺已不存在");
            }
            PostmanShopRelation shopRelation = PostmanShopRelationMemory.getInstance().getPostmanShopList(toUsername, shopInfo.getOwnUsername());
            if (shopRelation == null) {
                return new ResultInfo("当前骑手未服务该店铺");
            }
        }

        if (!isSystem) {
            //发起者今日发起次数
            Long fromCount = 0l;
            StringBuffer sb = new StringBuffer();
            sb.append(" select count(1) as counts from ").append(PojoTables.ORDER_POSTMAN)
                    .append(" where fromUsername = '").append(fromUsername).append("' and delFlag =0  ")
                    .append(" and from_unixtime(createTime/1000,'%Y%m%d')=date_format(now(),'%Y%m%d') ");
            try {
                fromCount = UserDaoSql.getInstance().getCount(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("获取当前配送员转单数失败");
            }

            Integer canChangeCount = 2;
            // 获取该订单的商圈
            Long agentId = orderInfo.getAgentId();
            boolean isAgentSettings = false;// 是否使用商圈的设置
            boolean runNewRule = false;//跑新规则
            ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(orderInfo.getUsername());
            if (shopInfo == null) {
                shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            }
            // 如果门店不为空, 使用门店的最大可接单数量配置
            if (shopInfo != null && StringUtils.isNotEmpty(shopInfo.getMaxReorderPerDay())) {
                canChangeCount = Integer.parseInt(shopInfo.getMaxReorderPerDay());
                runNewRule = true;
            }
            if(!runNewRule) {
                if (ValidateUtil.isID(agentId)) {
                    OrderOverTimeInfo overTimeInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
                    if (null != overTimeInfo) {
                        canChangeCount = overTimeInfo.getPostmanCanChangeCountPreDay();
                        isAgentSettings = true;
                    }
                }
                if (!isAgentSettings && null != SYS_SETTINGS.POSTMAN_CAN_CHANGE_COUNT_PRE_DAY && SYS_SETTINGS.POSTMAN_CAN_CHANGE_COUNT_PRE_DAY >= 0) {
                    canChangeCount = SYS_SETTINGS.POSTMAN_CAN_CHANGE_COUNT_PRE_DAY;
                }
            }

            if (fromCount >= canChangeCount) {
                return new ResultInfo("今日转单次数达到上限，无法转单");
            }
        }

        if (ValidateUtil.isNotNull(fromPostman.getCity()) && ValidateUtil.isNotNull(toPostman.getCity()) && !fromPostman.getCity().equalsIgnoreCase(toPostman.getCity())) {
            return new ResultInfo("被转对象不在可转范围内，请更换");
        }

        //判断订单状态是否可以操作
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL_BY_SYSTEM == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()) {
            return new ResultInfo("该状态不允许操作");
        }

        OrderPostmanInfo orderPostman = new OrderPostmanInfo();
        orderPostman.setOrderNo(orderNo);
        orderPostman.setFromId(fromPostman.getId());
        orderPostman.setFromUsername(fromPostman.getUsername());
        orderPostman.setToId(toPostman.getId());
        orderPostman.setToUsername(toPostman.getUsername());
        orderPostman.setCreateTime(DateUtils.getCurrTime());

        orderPostman.setDelFlag(0);
        orderPostman.setCreateUser(opUsername);

        boolean isNeedAccept = true; // 骑手是否需要接单
        if (!OrderMan.systemOperatePostmanNeedAccept()) {
            isNeedAccept = false;
            orderPostman.setIsSure(1);
        } else {
            orderPostman.setIsSure(0);
        }

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.ORDER_POSTMAN, orderPostman);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("转单失败，请稍后再试");
        }
        OrderInfoMemory.getInstance().changeToPostman(orderNo, toUsername);

        Long time = DateUtils.getCurrTime();
        //订单详情更改
        StringBuffer sbOrder = new StringBuffer();
        sbOrder.append("update ").append(PojoTables.OrderInfo).append(" set updateUser='").append(opUsername).append("'");
        if (!isNeedAccept && isSystem) {
            UserInfo toPost = UserInfoMemory.getInstance().getUserInfo(toUsername);
            if (null == toPost) {
                return new ResultInfo("被转用户不存在，请查证");
            }

            // 获取当前订单状态，继续当前骑手的订单状态往下走
            sbOrder.append(",postmanSureTime=").append(time)
                    .append(",postmanUsername='").append(toUsername).append("',postmanName='").append(toPost.getName())
                    .append("',postmanPhone='").append(toPost.getTelPhone()).append("',postmanImageUrl='").append(toPost.getSignPhoto()).append("'");
        } else {
            sbOrder.append(",changePostman='").append(toUsername).append("'")
                    .append(",changePostmanTime =").append(DateUtils.getCurrTime());
        }
        sbOrder.append(" where delFlag = 0 and orderNo = '").append(orderNo).append("'");
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("数据库连接异常");
        }

        boolean isUpdatePay = false;
        try {
            UserDaoSql.getInstance().executeBySql(sbOrder.toString(), con);
            if (!isNeedAccept && isSystem) {
                OrderStatus orderStatus2 = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, opUsername, time);
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus2, con);
            }
            con.commit();
        } catch (Exception e) {
            UserDaoSql.getInstance().rollback(con);
            e.printStackTrace();
            return new ResultInfo("转单失败，请稍后再试。");
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        if (!isNeedAccept && isSystem) {
            OrderStatusMemory.getInstance().addStatus(orderNo);

            // 将订单从上一个骑手的缓存中清楚
            OrderInfoMemory.getInstance().removePostmanOrderInfo(fromUsername, orderNo);
        }
        if (isUpdatePay) {
            OrderPayMemory.getInstance().modify(orderNo);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }
        return new ResultInfo();
    }

    // 骑手将订单退回订单大厅
    public static void postmanBackOrder(OrderInfo info, UserInfo user, CityPostman postman, boolean isCheckTime) throws
            Exception {

        if (ValidateUtil.isNotNull(info.getChangePostman())) {
//            return AjaxResult.errorResult("当前正在转单,无法操作");
            throw new Exception("当前正在转单,无法操作");
        }
        long time = DateUtils.getCurrTime();
        if (isCheckTime) {
            // 时间
            if (info.getPostmanBackOrderTime() == null || info.getPostmanBackOrderTime() == 0) {
                if (time - info.getPostmanSureTime() > SYS_SETTINGS.POSTMAN_CAN_BACK_TIME * 60 * 1000L) {
                    throw new Exception("时间已经超时,您无法退回订单");
                }
            } else {
                if (time - info.getPostmanSureTime() > info.getPostmanBackOrderTime() * 60 * 1000L) {
                    throw new Exception("您无法将订单退回订单大厅");
                }
            }
            long count = 0;
            StringBuilder countsql = new StringBuilder();
            countsql.append("select count(*) as counts  from ").append(PojoTables.ORDER_POSTMAN_BACK)
                    .append(" where username = '").append(user.getUsername()).append("' and delFlag =0  ")
                    .append(" and from_unixtime(createTime/1000,'%Y%m%d')=date_format(now(),'%Y%m%d') ");
            try {
                count = UserDaoSql.getInstance().getCount(countsql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                throw new Exception("获取当前配送员转单数失败");
            }
            if (count > SYS_SETTINGS.POSTMAN_CAN_BACK_COUNT_PRE_DAY) {
                throw new Exception("超出了今天退单次数");
            }
        }

        List<OrderStatus> orderStatusList = OrderStatusMemory.getInstance().list(info.getOrderNo());
        if (orderStatusList == null) {
            throw new Exception("订单异常,请联系客服");
        }
        int orderStatus = ORDER_STATUS.SHOP_SURE;
        if (info.getOrderStatus() == ORDER_STATUS.SHOP_SURE || info.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN) {

        } else if (ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP == info.getOrderStatus() || info.getOrderStatus() == ORDER_STATUS.POSTMAN_ARRIVED) {
            orderStatus = ORDER_STATUS.PAYED;
        } else {
            orderStatus = ORDER_STATUS.SHOP_SURE;
        }
        OrderPostmanBackInfo backInfo = new OrderPostmanBackInfo();
        // 退单生成记录
        backInfo.setBackTime(time).setDelFlag(0).setCreateTime(time).setCreateUser(user.getUsername()).setOrderNo(info.getOrderNo())
                .setPostmanName(user.getName()).setPostmanId(postman.getId()).setPostmanPhone(user.getTelPhone()).setPostmanImageUrl(user.getSignPhoto());
        // 退单记录
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = '").append(user.getUsername()).append("'")
                .append(", orderStatus = '").append(orderStatus).append("'")
                .append(", postManUsername = '',postmanName='',postmanPhone='',postmanImageUrl='',postmanSureTime=NULL")
                .append(", extra2 ='").append(postman.getUsername()).append("'")
                .append(" where orderNo = '").append(info.getOrderNo()).append("'").append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
            UserDaoSql.getInstance().saveObj(PojoTables.ORDER_POSTMAN_BACK, backInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("操作失败,请稍后重试");
        }
        OrderInfoMemory.getInstance().modifyStatus(info.getOrderNo());
        PostmanGrabMemory.getInstance().removeGrab(info.getPostManUsername(), info.getOrderNo());
    }

    // 多店铺提交订单 相关判断*********************************************
    // 是不是子的聚合订单
    public static boolean isMultipleSonOrder(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return false;
        }
        if ((ValidateUtil.isNotNull(orderInfo.getParentOrderNo()) && orderInfo.getOrderNo().startsWith("T"))
                || (ValidateUtil.isNotNull(orderInfo.getParentOrderNo()) && orderInfo.getOrderNo().startsWith("S"))
                || (orderInfo.getGroupState() != null && orderInfo.getGroupState() == ORDER_GROUP_STATE.GROUP_STATE_SON)) {
            return true;
        }
        return false;
    }

    public static boolean isMultipleSonOrder(String orderNo) {
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (info == null) {
            return false;
        }
        return isMultipleSonOrder(info);
    }

    public static boolean isMultipleParentOrder(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return false;
        }
        if ((ValidateUtil.isNotNull(orderInfo.getOrderNo()) && orderInfo.getOrderNo().startsWith("P"))
                ||
                (orderInfo.getGroupState() != null && orderInfo.getGroupState() == ORDER_GROUP_STATE.GROUP_STATE_PARENT)) {
            return true;
        }
        return false;
    }

    public static boolean isMultipleParentOrder(String orderNo) {
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (orderInfo == null) {
            return false;
        }
        return isMultipleParentOrder(orderInfo);
    }


    // 系统操作订单骑手不需要骑手操作
    public static boolean systemOperatePostmanNeedAccept() {
        if (SYS_SETTINGS.SYSTEM_OPERATE_NOT_NEED_ACCEPT != null && SYS_SETTINGS.SYSTEM_OPERATE_NOT_NEED_ACCEPT == 1) {
            return false;
        }
        return true;
    }

    // 是否有交集
    public static boolean isSetCross(Set<Long> set1, Set<Long> set2) {
        if (set1 == null || set1.isEmpty() || set2 == null || set2.isEmpty()) {
            return false;
        }
        for (Long id : set1) {
            if (set2.contains(id)) {
                return true;
            }
        }
        return false;
    }

    // 一乙项目  骑士配送费计算
    public static boolean updateOrderCompanyDeliveryPrice(Long companyId, String postmanUsername, OrderInfo
            orderInfo, String opUser, boolean isUpdateCount, Connection conn) throws Exception {
        if (orderInfo == null || conn == null) {
            throw new Exception("信息不全");
        }
        PostCompanyInfo postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        if (postCompanyInfo == null) {
            throw new Exception("配送公司信息为空");
        }
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != null && SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser='").append(opUser).append("'");
            ShopSignCompanyFeeInfo info = ShopSignCompanyService.getInstance().get(companyId, orderInfo.getShopId(), orderInfo.getOrderType());
            Double baseDeliveryPrice = 0.0d;
            Double fcDeliveryPrice = 0.0d;
            if (info == null) {
                // 默认到平台的
                baseDeliveryPrice = orderInfo.getDeliveryPrice();
                fcDeliveryPrice = orderInfo.getDeliveryPrice();
            } else {
                baseDeliveryPrice = info.getPrice();
                if (baseDeliveryPrice >= orderInfo.getDeliveryPrice()) {
                    fcDeliveryPrice = baseDeliveryPrice;
                } else {
                    fcDeliveryPrice = orderInfo.getDeliveryPrice();
                }
            }
            sb.append(",baseDeliveryPrice=").append(baseDeliveryPrice)
                    .append(",fcDeliveryPrice=").append(fcDeliveryPrice);
            // 分成等计算
            DeliverCompanySalarySerivce.SalaryDistributeTO salaryDisributeTO = DeliverCompanySalarySerivce.getInstance().getDeliverMoney(companyId, postmanUsername, fcDeliveryPrice);
            sb.append(",companyAllowance = ").append(salaryDisributeTO.getAllowance());
            sb.append(" where  delFlag = 0 and orderNo ='").append(orderInfo.getOrderNo()).append("'");
            UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
            // 分成添加一条
            OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
            if (orderPayInfo == null) {
                OrderPayInfo orderPay = new OrderPayInfo();
                orderPay.setCreateUser(opUser).setCreateTime(DateUtils.getCurrTime()).setDelFlag(0).setPostman(postmanUsername).setPostmanMoney(salaryDisributeTO.getPostMoney())
                        .setPlateAllowance(orderInfo.getPlateAllowance()).setCompanyAllowance(salaryDisributeTO.getAllowance())
                        .setPostCompanyId(companyId).setPostCompanyMoney(salaryDisributeTO.getCompanyMoney()).setOrderNo(orderInfo.getOrderNo())
                        .setPostRuleCountExplain((ValidateUtil.isNull(salaryDisributeTO.getRuleSetting()) ? "" : salaryDisributeTO.getRuleSetting()) + ":"
                                + (ValidateUtil.isNull(salaryDisributeTO.getRuleCount()) ? "" : salaryDisributeTO.getRuleCount()) + ":"
                                + salaryDisributeTO.getOrderCount() != null ? "" : salaryDisributeTO.getOrderCount() + "");
                UserDaoSql.getInstance().saveObj(PojoTables.OrderPay, orderPay, conn);
            } else {
                String postRuleCount = (ValidateUtil.isNull(salaryDisributeTO.getRuleSetting()) ? "" : salaryDisributeTO.getRuleSetting()) + ":"
                        + (ValidateUtil.isNull(salaryDisributeTO.getRuleCount()) ? "" : salaryDisributeTO.getRuleCount()) + ":"
                        + salaryDisributeTO.getOrderCount() != null ? "" : salaryDisributeTO.getOrderCount() + "";
                StringBuilder sql = new StringBuilder();
                sql.append("update ").append(PojoTables.OrderPay).append(" set updateUser = '").append(opUser).append("'")
                        .append(",postCompanyId=").append(companyId).append(",postCompanyMoney=").append(salaryDisributeTO.getCompanyMoney())
                        .append(",plateAllowance=").append(orderInfo.getPlateAllowance()).append(",companyAllowance=").append(salaryDisributeTO.getAllowance())
                        .append(",postman='").append(postmanUsername).append("',postmanMoney=").append(salaryDisributeTO.getPostMoney())
                        .append(",postRuleCountExplain='").append(postRuleCount).append("'")
                        .append(" where orderNo = '").append(orderInfo.getOrderNo()).append("' and delFlag = 0");
                UserDaoSql.getInstance().executeBySql(sql.toString());
            }
            // 更新单量
            if (isUpdateCount) {
                DeliverCompanySalarySerivce.getInstance().addUpOrderCount2PostMan(companyId, postmanUsername);
            }
            return true;
        }
        return false;
    }

    // 极光推送
    public static void orderJPushToPostman(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return;
        }
        if (orderInfo.getIsZiQu() == 1 || (orderInfo.getShopSelfPost() != null && orderInfo.getShopSelfPost() == 1)) {
            return;
        }
        HashSet<String> hashSet = UserAgentRelationMemory.getInstance().usernameSetOfAgentId(orderInfo.getAgentId());
        // 1.首先查看调度模式
        /*int modeByAdmin = GrabOrderModeMan.getGrabOrderModeByAdmin((hashSet == null || hashSet.isEmpty()) ? "" : hashSet.iterator().next());
        if (modeByAdmin == GRAB_ORDER_MODE.ONLY_DISPATCH_MODE   // 仅调度模式
                || (modeByAdmin == GRAB_ORDER_MODE.DISPATCH_FIRST_TO_OTHER && orderInfo.getDispatchState() != null && orderInfo.getDispatchState() == 2)) { // 调度优先模式 并且是抢单大厅里的订单
            return;
        }*/
        // 2. 获取所有的配送员列表

        if (SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT != null && SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT == POSTMAN_IN_CITY_OR_AGENT_DATA.CITY) {
            // List<CityPostman> cityPostmanList = CityPostmanMemory.getInstance().listOfCity(ValidateUtil.isNull(orderInfo.getCity()) ? orderInfo.getShopCity() : orderInfo.getCity());
            // if (ValidateUtil.isAbsList(cityPostmanList)) {
            //     postmanSet = cityPostmanList.stream().map(b -> b.getUsername()).collect(Collectors.toSet());
            // }
            JPushMessage jPushMessage = new JPushMessage(true, orderInfo.getShopCity(), "又有新的订单了", "又有新的订单了，快去抢单吧");
            jPushMessage.setPushUserType(JPushMessage.POSTMAN);//推给配送员
            jPushMessage.setJpSubType("");
            JPushTask.jPushMessageList.add(jPushMessage);
            return;
        } else if (SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT != null && SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT) {
            Set<String> postmanSet = new HashSet<>();
            List<String> tmpList = PostmanAgentRelationMemory.getInstance().listOfAgentId(orderInfo.getAgentId());
            if (ValidateUtil.isAbsList(tmpList)) {
                postmanSet = new HashSet<>(tmpList);
            }
            if (postmanSet != null && postmanSet.size() > 0) {
                postmanSet = postmanSet.stream().filter(b -> {
                    CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(b);
                    if (cityPostman == null || cityPostman.getIsLock() == 1 || cityPostman.getIsWork() == 0) {
                        return false;
                    }
                    return true;
                }).collect(Collectors.toSet());
            }
            // 3. 推送
            if (postmanSet != null && postmanSet.size() > 0) {
                // 给骑手发送一条通知
                JPushMessage jPushMessage = new JPushMessage(false, null, "又有新的订单了", "又有新的订单了，快去抢单吧");
                jPushMessage.setUsernameList(new ArrayList<>(postmanSet));
                jPushMessage.setPushUserType(JPushMessage.POSTMAN);
                jPushMessage.setJpSubType("");
                JPushTask.jPushMessageList.add(jPushMessage);
            }
        }
    }

    // 团购订单取消订单
    public static ResultInfo cancelGroupOrder(String sysAppKey, OrderInfo orderInfo, String
            cancelReason, String opUser) {
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL_BY_SYSTEM == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()) {
            return new ResultInfo("当前状态下不允许操作");
        }
        OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
        if (null == orderPayInfo || 0 == orderPayInfo.getIsPaid()) {
            return OrderMan.cancelOrderDirect(orderInfo, opUser, cancelReason, ORDER_STATUS.CANCEL, false, true);
        } else {
            return OrderMan.cancelOrder(sysAppKey, orderInfo, opUser, StringUtils.isEmpty(cancelReason) ? "" : cancelReason);
        }
    }

    // 聚合订单取消订单申请
    public static ResultInfo multipleOrderCancelApply(String sysAppKey, OrderInfo orderInfo, String
            cancelReason, String opUser) {
        HashSet<String> orderSet = OrderInfoMemory.getInstance().getOrderNoByPayNo(orderInfo.getOrderNo());
        if (orderSet == null) {
            orderSet = new HashSet<>();
        }
        orderSet.add(orderInfo.getOrderNo());
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            UserDaoSql.getInstance().close(con);
            return new ResultInfo(e.getMessage());
        }

        Set<String> orderSet2 = orderSet.stream().map(b -> {
            return ("'" + b + "'");
        }).collect(Collectors.toSet());

        String cancelR = "";
        if (ValidateUtil.isNotNull(cancelReason)) {
            cancelR = ",cancelReason='" + cancelReason + "'";
        }
        //更新订单信息
        StringBuffer sb = new StringBuffer();
        sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.APPLY).append(cancelR)
                .append(",updateUser ='").append(opUser).append("'  where delFlag = 0 and orderNo in (").append(StringUtils.join(orderSet2, ",")).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString(), con);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            UserDaoSql.getInstance().close(con);
            return new ResultInfo(e.getMessage());
        }
        //添加一条订单状态
        Long tim = DateUtils.getCurrTime();
        try {
            for (String orderNo : orderSet) {
                OrderStatus status = new OrderStatus(orderNo, ORDER_STATUS.PAYED_APPLY_CANCEL, opUser, tim);
                status.setNote(cancelReason);
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, con);
            }
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return new ResultInfo(e.getMessage());
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        for (String orderNo : orderSet) {
            //修改订单信息缓存
            OrderInfoMemory.getInstance().modifyStatus(orderNo);
            //修改订单状态信息缓存
            OrderStatusMemory.getInstance().addStatus(orderNo);
            //先取消自动完成
            if (ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus() || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()) {
                OverOrderThread.map.remove(orderNo);
            }
        }

        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已申请取消，请耐心等待审核");

        for (String orderNo : orderSet) {
            OrderInfo tOrder = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            // 给商家推送有退款申请
            if (tOrder != null && ValidateUtil.isID(tOrder.getShopId())) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
                if (null != shopInfo) {
                    Notice.publishNotice2Person(sysAppKey, shopInfo.getOwnUsername(), JPushMessage.SHOP_OWNER, "-4", NoticeType.order, "申请退款", "您店铺的订单（订单编号：" + orderNo + "）用户申请取消订单", orderNo);
                }
            }
        }

        // 有配送员的话，推送给配送员
        if (ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getPostManUsername(), JPushMessage.POSTMAN, "-4", NoticeType.order, "申请退款", "您的订单（订单编号：" + orderInfo.getOrderNo() + "）用户申请退款", orderInfo.getOrderNo());
        }
        return new ResultInfo();
    }

    // 查看当前订单是否所有的都已经取消了
    private static boolean checkAllPassCancel(String pOrderNo, String orderNo) {
        HashSet<String> orderSet = OrderInfoMemory.getInstance().getOrderNoByPayNo(pOrderNo);
        if (orderSet == null || orderSet.size() < 1) {
            return true;
        }
        for (String tmpOrder : orderSet) {
            if (pOrderNo.equals(tmpOrder) || orderNo.equals(tmpOrder)) {
                continue;
            }
            OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(tmpOrder);
            if (info == null) {
                continue;
            }
            if (info.getIsRefundApply() != REFUND_APPLY_STATUS.PASS) {
                return false;
            }
        }
        return true;
    }

    // 商家同意子订单取消订单了
    public static ResultInfo shopPassSonOrderCancelApply(String sysAppKey, OrderInfo orderInfo,
                                                         boolean pass, String reBackReason, String opUser) {
        if (!OrderMan.isMultipleSonOrder(orderInfo)) {
            return new ResultInfo();
        }
        if (ValidateUtil.isNull(orderInfo.getPayOrderNo())) {
            return new ResultInfo("支付单号为空~");
        }
        if (pass) {
            // 先同意了
            StringBuffer sb = new StringBuffer();
            sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.PASS)
                    .append(",extra3 = orderStatus").append(",orderStatus = ").append(ORDER_STATUS.PAYED_CANCEL)
                    .append(",updateUser ='").append(opUser).append("'").append("  where delFlag = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo("操作失败，请稍后再试");
            }
            //修改订单信息缓存
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            if (checkAllPassCancel(orderInfo.getPayOrderNo(), orderInfo.getOrderNo())) {
                // 退款~~~
                return passCancelMultipleOrder(sysAppKey, orderInfo.getParentOrderNo(), opUser);
            }
        } else {
            // 拒绝退款
            return refuseCancelMultipleOrder(sysAppKey, orderInfo, reBackReason, opUser);
        }
        return new ResultInfo();
    }

    private static ResultInfo passCancelMultipleOrder(String sysAppKey, String pOrderNo, String opUser) {
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(pOrderNo);
        if (orderInfo == null) {
            return new ResultInfo("未获取到订单" + pOrderNo);
        }

        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(pOrderNo);
        // 取消订单
        ResultInfo resultInfo = cancelOrder(sysAppKey, orderInfo, opUser, null, true, true, false);
        if (null == resultInfo || !resultInfo.isSuccess()) {
            return resultInfo;
        }
        StringBuffer sb = new StringBuffer();
        sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.PASS)
                .append(",updateUser ='").append(opUser).append("'  where delFlag = 0 and orderNo = '").append(pOrderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo(e.getMessage());
        }
        return new ResultInfo();
    }

    // todo : 拒绝退款
    private static ResultInfo refuseCancelMultipleOrder(String sysAppKey, OrderInfo orderInfo, String
            reBackReason, String opUser) {
        if (orderInfo == null) {
            return new ResultInfo("未获取到订单");
        }
        HashSet<String> tempSet = OrderInfoMemory.getInstance().getOrderNoByPayNo(orderInfo.getPayOrderNo());
        Set<String> orderSet = new HashSet<>();
        if (tempSet != null && !tempSet.isEmpty()) {
            orderSet.addAll(tempSet);
        }
        orderSet.remove(orderInfo.getOrderNo());
        orderSet.remove(orderInfo.getPayOrderNo());
        Set<String> orderSet2 = orderSet.stream().map(b -> {
            return ("'" + b + "'");
        }).collect(Collectors.toSet());
        // 获取父订单的订单状态
        OrderInfo pOrder = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getPayOrderNo());
        Integer orderstatus = ORDER_STATUS.SHOP_SURE;
        if (pOrder != null) {
            orderstatus = pOrder.getOrderStatus();
        }
        if (orderSet.size() > 0) {
            Connection con = null;
            try {
                con = UserDaoSql.getInstance().getConnection(true);
                // 1. 退出原来的
                StringBuffer sb = new StringBuffer();
                sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.NO_PASS)
                        .append(",updateUser ='").append(opUser).append("',reBackReason='").append(reBackReason)
                        .append("'  where delFlag = 0 and orderNo in (").append("'" + orderInfo.getOrderNo() + "','" + orderInfo.getPayOrderNo() + "'").append(")");
                UserDaoSql.getInstance().executeBySql(sb.toString(), con);
                // 2.之前统一的
                StringBuffer sb2 = new StringBuffer();
                sb2.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.NO_PASS)
                        .append(",updateUser ='").append(opUser).append("',orderStatus=").append(orderstatus)
                        .append("  where delFlag = 0 and orderNo in (").append(StringUtils.join(orderSet2, ",")).append(")");
                UserDaoSql.getInstance().executeBySql(sb2.toString(), con);
                con.commit();
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(con);
            } finally {
                UserDaoSql.getInstance().close(con);
            }

            //修改订单信息缓存
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getPayOrderNo());
            for (String tOrder : orderSet) {
                OrderInfoMemory.getInstance().modifyStatus(tOrder);
            }
            //加入自动完成订单
            if (ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus() || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()) {
                OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getPayOrderNo());
                if (info != null) {
                    OverOrderThread.map.put(info.getOrderNo(), info);
                }
            }
        } else {
            //更新订单信息
            StringBuffer sb = new StringBuffer();
            sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.NO_PASS)
                    .append(",updateUser ='").append(opUser).append("',reBackReason='").append(reBackReason)
                    .append("'  where delFlag = 0 and orderNo in (").append("'" + orderInfo.getOrderNo() + "','" + orderInfo.getPayOrderNo() + "'").append(")");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo(e.getMessage());
            }

            //修改订单信息缓存
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getPayOrderNo());

            //加入自动完成订单
            if (ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus() || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()) {
                OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getPayOrderNo());
                if (info != null) {
                    OverOrderThread.map.put(info.getOrderNo(), info);
                }
                OverOrderThread.map.put(orderInfo.getOrderNo(), orderInfo);
            }
        }
        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderInfo.getPayOrderNo() + "），申请取消未通过");
        return new ResultInfo();
    }



    // 取消保单数据
    private static void cancelPolicy(String orderNo, String updateUser) {
        List<PolicyInfo> db_list = OrderPolicyRecordMemory.getInstance().listOfOrderNo(orderNo);
        if (!ValidateUtil.isAbsList(db_list)) {
            System.out.println("未获取到保单信息");
            return;
        }
        if (db_list.get(0).getIsCancel() == 1) {
            return;
        }
        Set<Integer> orderStatusSet = new HashSet<>();
        for (PolicyInfo info : db_list) {
            Integer status = cancelPolicyOne(info);
            orderStatusSet.add(status);
        }
        String updateSql = "update " + PojoTables.OrderInfo + " set ";
        if (orderStatusSet.size() == 1) {
            updateSql += " insuranceStatus = " + orderStatusSet.iterator().next();
        } else {
            System.out.println("取消订单成功!~ 但是发送取消保险存在异常~~~");
            updateSql += " insuranceStatus = " + INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR;
        }
        updateSql += " where orderNo = '" + orderNo + "' and delFlag = 0";
        try {
            UserDaoSql.getInstance().executeBySql(updateSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
    }

    // 取消保险
    private static int cancelPolicyOne(PolicyInfo info) {
        Integer status = 0;
        try {
            cancelThreadPolicy(info);
            status = INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.BACK_DEALING;
        } catch (Exception e) {
            e.printStackTrace();
            status = INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR;
        }
        String sql = "update " + PojoTables.ORDER_POLICY_RECORD + " set status = " + status + " where id = " + info.getId() + " and delFlag = 0";
        try {
            UserDaoSql.getInstance().executeBySql(sql);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("取消保险存在异常~~~~");
        }
        OrderPolicyRecordMemory.getInstance().addOrModify(info.getOrderNo());
        return status;
    }

    /**
     * //     * 取消第三方的保险
     * //     *
     * //     * @param policyInfos
     * //     * @param updateUser
     * //
     */
    private static void cancelThreadPolicy(PolicyInfo policyInfo) throws Exception {
        // 发送的保单信息
        PolicyOrderDto orderDto = new PolicyOrderDto();
        BeanUtils.copyProperties(policyInfo, orderDto);
        orderDto.setOrderNo(policyInfo.getOrderNoIndex());

        List<InsuredsDto> insuredsDtoList = new ArrayList<>();
        InsuredsDto insuredsDto = new InsuredsDto();
        BeanUtils.copyProperties(policyInfo, insuredsDto);
        insuredsDtoList.add(insuredsDto);

        String url = SYS_CONFIG_PATH.BAO_XIAN_SERVICE_URL + "/policy/receiveJson/cancelPolicy";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("order", orderDto);
        jsonObject.put("insureds", insuredsDtoList);
        String resultJson = HttpRequest.sendHttpPostJson(url, jsonObject);
        System.out.println("取消保单报文---->" + resultJson);
        if (resultJson == null) {
            throw new Exception("取消保单服务器未响应");
        }
        JSONObject object = JSONObject.parseObject(resultJson);
        if (object.get("status") == null || ValidateUtil.isNull(object.get("status")) || Integer.parseInt(object.get("status").toString()) != 1) {
            throw new Exception(object.get("error") == null ? "" : object.get("error").toString());
        }
    }

    /**
     * 判断是否是骑手服务店铺的订单
     *
     * @param orderInfo
     * @return
     */
    public static boolean isPostmanServicesShopOrder(OrderInfo orderInfo) {
        return (SYS_SETTINGS.POSTMAN_SERVICE_SHOP != null && SYS_SETTINGS.POSTMAN_SERVICE_SHOP == 1 && orderInfo != null && orderInfo.getOrderType() != null && ((orderInfo.getOrderType() - ORDER_TYPE.PAO_TUI == 0 && orderInfo.getIsShopPaoTuiOrder() == 1) || orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS == 0));
    }

    //配送员接单或拒绝接单
    public static ResultInfo postmanSureOrRefuse(String orderNo, String username, Integer isSure) {
        if (ValidateUtil.isNull(orderNo) || ValidateUtil.isNull(username)) {
            return new ResultInfo("信息不完整，请稍后再试");
        }
        if (null == isSure) {
            return new ResultInfo("请选择操作类型，请稍后再试");
        }

        if (0 == isSure) {
            return new ResultInfo("操作类型不正确，请稍后再试");
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        if (null == postman) {
            return new ResultInfo("您无权操作");
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return new ResultInfo("订单不存在，请稍后再试");
        }

        if (ValidateUtil.isNull(orderInfo.getChangePostman())) {
            //是否为转抢
            if (null != orderInfo.getIsReGrab() && 0 == ORDER_RELAY_TYPE.ING - orderInfo.getIsReGrab()) {
                //转抢中
            }

            return new ResultInfo("该订单未发起转单");
        }
        if (!username.equalsIgnoreCase(orderInfo.getChangePostman())) {
            return new ResultInfo("您不是被转对象无法操作");
        }
        String oldPostman = orderInfo.getPostManUsername();

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {
            return new ResultInfo("当前用户信息有误");
        }

        Connection co = null;
        // 事务
        try {
            co = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("数据库连接异常");
        }
        //更新转单信息
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.ORDER_POSTMAN).append(" set isSure = ").append(isSure).append(",sureTime=").append(DateUtils.getCurrTime())
                .append(",updateUser='").append(username).append("' where orderNo = '").append(orderNo)
                .append("' and delFlag = 0 and isSure = 0 and toUsername = '").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString(), co);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(co);
            UserDaoSql.getInstance().close(co);
            return new ResultInfo("接单失败，请稍后再试");
        }

        switch (isSure) {
            case OrderPostmanInfo.SURE: {//接单
                String phone = userInfo.getTelPhone();
                if (ValidateUtil.isNull(phone)) {
                    phone = username;
                }
                String poto = userInfo.getSignPhoto();
                if (ValidateUtil.isNotNull(poto) && ValidateUtil.isNetUrl(poto)) {
                    poto = poto.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
                }
                //删除订单中的正在转单人
                StringBuffer sbOrder = new StringBuffer();
                sbOrder.append("update ").append(PojoTables.OrderInfo).append(" set postmanUsername='").append(username)
                        .append("',postmanName='").append(userInfo.getName()).append("',postmanPhone='").append(phone)
                        .append("',postmanImageUrl='").append(poto).append("',changePostman=null,changePostmanTime=NULL,updateUser='").append(username)
                        .append("' where delFlag = 0 and orderNo = '").append(orderNo).append("'");
                boolean isUpdatePayInfo = false;
                try {
                    UserDaoSql.getInstance().executeBySql(sbOrder.toString(), co);

                    co.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(co);
                    return new ResultInfo("接单失败，请稍后再试.");
                } finally {
                    UserDaoSql.getInstance().close(co);
                }
                OrderInfoMemory.getInstance().modifyStatus(orderNo);//更新订单信息
                // 更新订单的信息
                if (isUpdatePayInfo) {
                    OrderPayMemory.getInstance().modify(orderNo);
                    try {
                        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                        JmsSender.setTopicSender(notify);
                    } catch (Exception e) {
                    }
                }
                //删除之前配送员订单列表里的该订单
                OrderInfoMemory.getInstance().removePostmanOrderInfo(oldPostman, orderNo);
            }
            break;
            case OrderPostmanInfo.REFUSE: {//拒绝接单
                //删除订单中的正在转单人
                StringBuffer sbOrder = new StringBuffer();
                sbOrder.append("update ").append(PojoTables.OrderInfo).append(" set changePostman=null,changePostmanTime=null,updateUser='").append(username)
                        .append("' where delFlag = 0 and orderNo = '").append(orderNo).append("'");

                try {
                    UserDaoSql.getInstance().executeBySql(sbOrder.toString(), co);
                    co.commit();
                } catch (SQLException e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(co);
                    return new ResultInfo("接单失败，请稍后再试.");
                } finally {
                    UserDaoSql.getInstance().close(co);
                }
                OrderInfoMemory.getInstance().modifyStatus(orderNo);//更新订单信息

                // 删除转单订单
                OrderInfoMemory.getInstance().postmanRefuseChangeOrder(username, orderNo);
            }
            break;
        }
        return new ResultInfo();
    }

    public static List<OrderInfoGoods> getGoodListByOrderNo(String orderNo){
        //添加商品列表数据
        List<OrderInfoGoods> voList = null;
        QueryCondition query = QueryCondition.getInstance();
        Expression expressions = Expression.getInstance().addChild("delFlag", 0).addChild("orderNo", orderNo);
        query.addCondition(expressions);
        String sql = DaoUtils.getSql(PojoTables.ORDER_ITEMS, query);
        try {
            voList = (List<OrderInfoGoods>) UserDaoSql.getInstance().list(OrderInfoGoods.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return voList;
    }
}
